python - Python 中十六进制字符串到有符号 int

标签 python python-3.x integer hex

如何在 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/

相关文章:

php - 在MySQL中添加使用列中的信息来创建变量?

python - 根据值和规则拆分整数列表的更好方法

c - SIMD signed with unsigned multiplication for 64-bit * 64-bit to 128-bit

python - 创建包含特定元素的数组列表

python - 将文档字符串放在 Python 属性上的正确方法是什么?

python - 抓取电子邮件地址时无法删除不需要的东西

python - 如何将 float 组更改为字符串数组,然后保存到txt

python - 全局变量 Python 类

Python PIL 加载抛出 AttributeError : 'NoneType' object has no attribute 'read'

c++ - 使用boost python的python模块是空的?