十六进制字符串到 Python 3.2 中的带符号整数? [英] Hex string to signed int in Python 3.2?

查看:16
本文介绍了十六进制字符串到 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 = 20
位 1 = 21
位 n-2 = 2n-2
位 n-1 = -2n-1

但是位 n-1 在无符号时的值为 2n-1,所以数字 2n 太高了.如果设置了第 n-1 位,则减去 2n:

But bit n-1 has value 2n-1 when unsigned, so the number is 2n too high. Subtract 2n 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 中的带符号整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆