Dealing With Very Large Hex Numbers In Python
I need to convert an extremely large number (760402852596084587359490684321824034940816612213847025986535451828145781910762684416) to hexadecimal in python, but it seems to round
Solution 1:
Are you sure it's wrong? you can test the code below. The results are the same:
def make_hex(a):
list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
output = []
while a>1:
output.append(list[a%16])
a = a//16output.reverse()
return'0x' + ''.join(output)
a = 760402852596084587359490684321824034940816612213847025986535451828145781910762684416print(make_hex(a))
print(hex(a))
Solution 2:
I tried your original number by converting it with a different function and then adding 1 by 1.
Answer: Python isn't truncating, the hex of your number just happens to end in 0s:
>>>num=760402852596084587359490684321824034940816612213847025986535451828145781910762684416>>>to_bytes(num)
'643437346d684000000000000000000000000000000000000000000000000000000000'
>>>to_bytes(num+1)
'643437346d684000000000000000000000000000000000000000000000000000000001'
>>>to_bytes(num+2)
'643437346d684000000000000000000000000000000000000000000000000000000002'
Here's my to_bytes function for reference:
def to_bytes(i, count=0, endian='big'):
count = 1if i < 256elsemath.ceil(math.log(i + 1, 256))
return i.to_bytes(count, endian).hex()
Post a Comment for "Dealing With Very Large Hex Numbers In Python"