Skip to content

Instantly share code, notes, and snippets.

@philangist
Last active August 29, 2015 14:02
Show Gist options
  • Save philangist/2fbf0152e8b0bda4cda6 to your computer and use it in GitHub Desktop.
Save philangist/2fbf0152e8b0bda4cda6 to your computer and use it in GitHub Desktop.
Base 2 to Base 10 and Base 10 to Base 16 interger conversion
BASE_16 = 16
HEXADECIMAL_CHARACTERS = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
'A', 'B', 'C', 'D', 'E', 'F',
]
DECIMAL_TO_HEXADECIMAL_MAPPING = {
x: HEXADECIMAL_CHARACTERS[x]
for x in range(len(HEXADECIMAL_CHARACTERS))
}
def decimal_to_hexadecimal(decimal):
if decimal <= 255:
prefix = str(DECIMAL_TO_HEXADECIMAL_MAPPING[decimal/BASE_16])
suffix = str(DECIMAL_TO_HEXADECIMAL_MAPPING[decimal%BASE_16])
else:
prefix = decimal_to_hexadecimal(decimal/256)
suffix = decimal_to_hexadecimal(decimal%256)
return prefix + suffix
def bitstring_to_integer(bitstring):
bitstring = bitstring[::-1]
total = 0
for i in range(len(bitstring)):
total += long(bitstring[i]) * (2**i)
return int(total)
# 0 - 15 in binary
inputs = [
'0000', '0001', '0010', '0011',
'0100', '0101', '0110', '0111',
'1000', '1001', '1010', '1011',
'1100', '1101', '1110', '1111',
]
map(bitstring_to_integer, inputs)
map(decimal_to_hexadecimal, map(bitstring_to_integer, inputs))
bitstring_to_integer('10000000000000000')
# 65536
decimal_to_hexadecimal(bitstring_to_integer('10000000000000000'))
# '010000'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment