如何使 python 看起来像二进制补码的十六进制数?

How to make python look hex numbers as two's complemented?

我有一组十六进制正数和负数。我想将它们转换为十进制值:

>>> int("f107",16)
61703
>>> 

如何使 python 看起来 f107 为二进制补码?换句话说,我想要 -3833 而不是 61703。我怎样才能实现它?

struct.unpack(">h","f107".decode("hex"))

0xf107 = encode_to_bytes => "\xf1\x07"

由于它是两个字节,我们只需将其解压为 > 大端 h signed-short

这是一个非常简单的函数:

def twos_complement(n, w):
    if n & (1 << (w - 1)): n = n - (1 << w)
    return n

示例:

>>> twos_complement(61703, 16)
-3833

与 Joran 的回答不同,它支持任意位宽。