Created
May 23, 2019 18:59
-
-
Save brianredbeard/8efcb6767f8f5adfda7986f5ac1e36ea to your computer and use it in GitHub Desktop.
quicknum - a script to quickly convert/print binary, hex, and decimal numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| import re | |
| import sys | |
| x=sys.argv[1] | |
| # Check to see if the string is only binary | |
| nonbin = re.search(r'[2-9A-Fa-f]', x) | |
| # First, check to see if there were matches in binary, if not | |
| # Attempt to convert to an integer assuming base 10 if it | |
| # fails, attempt base 16 (hex) | |
| if nonbin is None: | |
| try: | |
| num = int(x, 2) | |
| except: | |
| print("Problem parsing value from", x) | |
| sys.exit(1) | |
| else: | |
| try: | |
| num = int(x) | |
| except: | |
| num = int(x, 16) | |
| hnum = ('{:010X}'.format(num)) | |
| print('Integer: {:40d}'.format(num)) | |
| print('Hex: {:>40s}'.format(hnum)) | |
| print('Binary: {0:40b}'.format(num)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment