Signed equivalent of a 2's complement hex value

南笙酒味 提交于 2019-12-24 05:38:30

问题


On the python terminal when I do :-

In [6]: 0xffffff85
Out[6]: 4294967173

In [9]: "%d" %(0xffffff85)
Out[9]: '4294967173'

I'd like to be able to give in 0xffffff85 and get the signed equivalent decimal number in python(in this case -123). How could I do that?

In C, I could do it as :-

int main() { int x = 0xffffff85; printf("%d\n", x); }

回答1:


You could do that using ctypes library.

>>> import ctypes
>>> ctypes.c_int32(0xffffff85).value
-123

You can also do the same using bitstring library.

>>> from bitstring import BitArray
>>> BitArray(uint = 0xffffff85, length = 32).int
-123L

Without external / internal libraries you could do :

int_size = 32
a = 0xffffff85
a = (a ^ int('1'*a.bit_length())) + 1 if a.bit_length() == int_size else a

This takes the 2's complement of the number a, if the bit_length() of the number a is equal to your int_size value. int_size value is what you take as the maximum bit length of your signed binary number [ here a ].

Assuming that the number is signed, an int_size bit negative number will have its first bit ( sign bit ) set to 1. Hence the bit_length will be equal to the int_size.



来源:https://stackoverflow.com/questions/25096755/signed-equivalent-of-a-2s-complement-hex-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!