Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Last active December 10, 2015 23:26
Show Gist options
  • Save matthewjberger/93a2a4c5ca1aa11e14e9 to your computer and use it in GitHub Desktop.
Save matthewjberger/93a2a4c5ca1aa11e14e9 to your computer and use it in GitHub Desktop.
Simple python converters for binary, hexadecimal, and decimal
# Converters
def hexToBin(h):
return bin(int(h,16))[2:]
def binToHex(b):
return '{:0{}X}'.format(int(b,2), len(b) // 4)
def decToBin(i):
s = ""
while i:
if i & 1:
s = "1" + s
else:
s = "0" + s
i = (i >> 1)
return s
def binToDec(b):
return int(b,2)
def decToHex(i):
return hex(a)[2:]
def hexToDec(i):
return int(i,16)
# Useful for formatted displays of binary numbers
def spaceBytes(b):
return ' '.join(b[i:i+4] for i in range(0,len(b), 4))
def quote(s):
return "\"" + s + "\""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment