本文介绍了十六进制字符串到 Python 3.2 中的带符号整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Python 3.2 中将十六进制字符串转换为有符号整数?
How do I convert a hex string to a signed int in Python 3.2?
我能想到的最好的是
h = '9DA92DAB'
b = bytes(h, 'utf-8')
ba = binascii.a2b_hex(b)
print(int.from_bytes(ba, byteorder='big', signed=True))
有没有更简单的方法?无符号就简单多了:int(h, 16)
Is there a simpler way? Unsigned is so much easier: int(h, 16)
顺便说一句,问题的起源是 itunes 持久 id - 音乐库 xml 版本和 iTunes hex 版本
BTW, the origin of the question is itunes persistent id - music library xml version and iTunes hex version
推荐答案
在n位二进制补码中,位有值:
In n-bit two's complement, bits have value:
位 0 = 2
位 1 = 2
位 n-2 = 2
位 n-1 = -2
但是位 n-1 在无符号时的值为 2,所以数字 2 太高了.如果设置了第 n-1 位,则减去 2:
But bit n-1 has value 2 when unsigned, so the number is 2 too high. Subtract 2 if bit n-1 is set:
>>> def twos_complement(hexstr,bits):
... value = int(hexstr,16)
... if value & (1 << (bits-1)):
... value -= 1 << bits
... return value
...
>>> twos_complement('FFFE',16)
-2
>>> twos_complement('7FFF',16)
32767
>>> twos_complement('7F',8)
127
>>> twos_complement('FF',8)
-1
这篇关于十六进制字符串到 Python 3.2 中的带符号整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!