我有一个十六进制的0xfffffffffffffffffffffffffffffffffffffffffffffffffffdf05d84162877
,用十进制表示应该是-580140491462537
。然而,做以下事情会导致糟糕的答案。有人能帮忙吗?
In: test = '0xfffffffffffffffffffffffffffffffffffffffffffffffffffdf05d84162877'
In: int(test,16)
Out: 11579208923731619542357098500868790785326998466564056403945758342777263817739
首先将字符串转换为字节。您将不得不删除前导";0x";。然后使用int.from_bytes并指定它是有符号的和big-endian。
In: int.from_bytes(bytes.fromhex(test[2:]), byteorder="big", signed=True)
Out: -580140491462537
我已经调整了这个答案
# hex string to signed integer
def htosi(val):
uintval = int(val, 16)
bits = 4 * len(val)
indicative_binary = 2 ** (bits)
indicative_binary_1 = 2 ** (bits-1)
if uintval >= indicative_binary_1:
uintval = int(0 - (indicative_binary - uintval))
return uintval
这确实需要一个纯十六进制字符串:
test1 = 'fffffffffffffffffffffffffffffffffffffffffffffffffffdf05d84162877'
print(htosi(test1))
-580140491462537