如何在Python中将负整数值转换为十六进制
我使用 python 2.6
>>> hex(-199703103)
'-0xbe73a3f'
>>> hex(199703103)
'0xbe73a3f'
正值和负值相同吗?
当我使用 calc 时,该值为 FFFFFFFFF418C5C1
。
I use python 2.6
>>> hex(-199703103)
'-0xbe73a3f'
>>> hex(199703103)
'0xbe73a3f'
Positive and negative value are the same?
When I use calc, the value is FFFFFFFFF418C5C1
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Python 的整数可以任意增大。为了按照您想要的方式计算原始二进制补码,您需要指定所需的位宽度。您的示例以 64 位二进制补码显示
-199703103
,但它也可能是 32 位或 128 位,从而导致不同数量的0xf
' s 开头。hex()
不会这样做。我建议使用以下替代方案:打印出:
Python's integers can grow arbitrarily large. In order to compute the raw two's-complement the way you want it, you would need to specify the desired bit width. Your example shows
-199703103
in 64-bit two's complement, but it just as well could have been 32-bit or 128-bit, resulting in a different number of0xf
's at the start.hex()
doesn't do that. I suggest the following as an alternative:This prints out:
由于 Python 整数是任意大的,因此您必须对这些值进行屏蔽,以将转换限制为 2 补码表示所需的位数。
Python 将
hex(-199703103)
的简单情况显示为负十六进制值 (-0xbe73a3f
),因为 2s 补码表示形式前面会有无数个 F对于任意精度数。掩码值 (2**32-1 == 0xFFFFFFFF) 限制了这一点:Because Python integers are arbitrarily large, you have to mask the values to limit conversion to the number of bits you want for your 2s complement representation.
Python displays the simple case of
hex(-199703103)
as a negative hex value (-0xbe73a3f
) because the 2s complement representation would have an infinite number of Fs in front of it for an arbitrary precision number. The mask value (2**32-1 == 0xFFFFFFFF) limits this:添加到 标记答案,如果您想要不同的输出格式,请使用
Adding to Marks answer, if you want a different output format, use
对于那些想要正数前导零的人,请尝试以下操作:
感谢@tm1 的灵感!
For those who want leading zeros for positive numbers, try this:
Thanks @tm1, for the inspiration!