Created
December 12, 2019 11:25
-
-
Save sebbekarlsson/cf785fac6553b373ec6abd5ad4694f34 to your computer and use it in GitHub Desktop.
This file contains 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
''' | |
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