如何在 Python 3 中将十六进制字符串转换为有符号整型?
我能想到的最好的是
h = '9DA92DAB'
b = bytes(h, 'utf-8')
ba = binascii.a2b_hex(b)
print(int.from_bytes(ba, byteorder='big', signed=True))
有没有更简单的方法?无符号更容易:int(h, 16)
顺便说一句,问题的起源是itunes persistent id - music library xml version and iTunes hex version
最佳答案
在 n 位二进制补码中,位具有值:
bit 0 = 20
bit 1 = 21
bit n-2 = 2n-2
bit n-1 = -2n-1
但是当无符号时,位 n-1 的值为 2n-1,因此该数字太高了 2n。如果设置了位 n-1,则减去 2n:
def twos_complement(hexstr, bits):
value = int(hexstr, 16)
if value & (1 << (bits - 1)):
value -= 1 << bits
return value
print(twos_complement('FFFE', 16))
print(twos_complement('7FFF', 16))
print(twos_complement('7F', 8))
print(twos_complement('FF', 8))
输出:
-2
32767
127
-1
关于python - Python 中十六进制字符串到有符号 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6727875/