Skip to content

Instantly share code, notes, and snippets.

@sebbekarlsson
Created December 12, 2019 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebbekarlsson/cf785fac6553b373ec6abd5ad4694f34 to your computer and use it in GitHub Desktop.
Save sebbekarlsson/cf785fac6553b373ec6abd5ad4694f34 to your computer and use it in GitHub Desktop.
'''
Simple example on how to manually convert hex to decimal without using
'int()' method.
'''
from functools import reduce
def to_decimal(hexnr):
assert hexnr.startswith('0x')
hextable = {'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15}
hexnr = hexnr.lower()
return reduce(lambda a, b: (a[1] if isinstance(a, tuple) else a) + b[1] * pow(16, b[0]),
[(i, int(hextable[c] if c in hextable else c) if i < len(hexnr) - 2 else 0)
for i, c in enumerate(hexnr[::-1])])
hexnr = '0x303e'
a = to_decimal(hexnr)
print(a)
b = int(hexnr, 16)
print(b)
assert a == b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment