在Python中将长十六进制字符串转换为十六进制数字

时间:2017-03-15 14:51:13

标签: python string hex

我有一个很长的十六进制字符串,例如'0x0000fffffffffffff000000000ffffff'。

如何将其转换为完全相同的十六进制数:0x0000fffffffffffff000000000ffffff

1 个答案:

答案 0 :(得分:0)

>>> eval('0x0000fffffffffffff000000000ffffff')
5192296858534826475608991739150335
>>> hex(eval('0x0000fffffffffffff000000000ffffff'))
'0xfffffffffffff000000000ffffff' #unnecessary zeros is omitted here

但是如果你需要得到一个固定长度为32位的数字,这里有解决方案:

def hex_op(hex_number):
    len_ = len(hex_number[2:])
    if len_ < 32: #checking if number has less than 32 digits
        return "0x" + "0"*(32-len_) + hex_number[2:]
    else:
        return hex_number

用法示例:

>>> hex_op('0xfffffffffffff000000000ffffff') # our number that we got from previous example
'0x0000fffffffffffff000000000ffffff'