将 hexstr 转换为有符号整数 - Python

Converting hexstr to signed integer - Python

我有这个 hexstr 0xfffffffffffffffffffffffffffffffffffffffffffffffffffdf05d84162877,按十进制计算它应该是 -580140491462537。但是,执行以下操作会导致错误的答案。有人可以帮忙吗?

In: test = '0xfffffffffffffffffffffffffffffffffffffffffffffffffffdf05d84162877'
In: int(test,16)
Out: 11579208923731619542357098500868790785326998466564056403945758342777263817739

我已经改编了这个answer

# 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

首先将字符串转换为字节。您必须删除前导“0x”。 然后使用 int.from_bytes 并指定它已签名和 big-endian.

In: int.from_bytes(bytes.fromhex(test[2:]), byteorder="big", signed=True)
Out: -580140491462537