Skip to content

Instantly share code, notes, and snippets.

@brianredbeard
Created May 23, 2019 18:59
Show Gist options
  • Save brianredbeard/8efcb6767f8f5adfda7986f5ac1e36ea to your computer and use it in GitHub Desktop.
Save brianredbeard/8efcb6767f8f5adfda7986f5ac1e36ea to your computer and use it in GitHub Desktop.
quicknum - a script to quickly convert/print binary, hex, and decimal numbers
#!/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