在python中处理非常大的十六进制数

时间:2019-05-24 21:01:57

标签: python hex

我需要转换一个非常大的数字

(760402852596084587359490684321824034940816612213847025986535451828145781910762684416)在python中为十六进制,但是当我运行hex(N)时似乎将其四舍五入。我应该做些什么?我已经尝试过float.hex,但是没有结果

所说的数字产生0x643437346d684000000000000000000000000000000000000000000000000000000000

生成的十六进制应该为0x643437346d696e3372535f43683334373372535f344e645f4c693452535f30685f6d79

from sys import argv
print(hex(int(argv[1])))

2 个答案:

答案 0 :(得分:0)

您确定这是错误的吗?您可以测试以下代码。结果是相同的:

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//16
    output.reverse()   
    return '0x' + ''.join(output)

a = 760402852596084587359490684321824034940816612213847025986535451828145781910762684416
print(make_hex(a))
print(hex(a))

答案 1 :(得分:0)

我尝试通过使用其他函数将原始数字转换为原始数字,然后将其乘以1的方法。

Python不会被截断,您的数字的十六进制恰好以0结尾:

>>> num=760402852596084587359490684321824034940816612213847025986535451828145781910762684416
>>> to_bytes(num)
'643437346d684000000000000000000000000000000000000000000000000000000000'
>>> to_bytes(num+1)
'643437346d684000000000000000000000000000000000000000000000000000000001'
>>> to_bytes(num+2)
'643437346d684000000000000000000000000000000000000000000000000000000002'

这是我的to_bytes函数供参考:

def to_bytes(i, count=0, endian='big'):
    count = 1 if i < 256 else math.ceil(math.log(i + 1, 256))
    return i.to_bytes(count, endian).hex()