2的补十六进制值的签名等同 [英] Signed equivalent of a 2's complement hex value
问题描述
在Python的终端时,我做的: -
在[6]:0xffffff85
出[6]:4294967173在[9]:%d个%(0xffffff85)
出[9]:'4294967173'
我希望能在 0xffffff85
给和蟒蛇获得相当于签订十进制数(在这种情况下, -123
)。我怎么能这样做呢?
在C,我能做到这一点的: -
INT的main(){INT X = 0xffffff85;的printf(%d个\\ N,X); }
您可能用的 ctypes的
库。
>>>进口ctypes的
>>> ctypes.c_int32(0xffffff85).value的
-123
您也可以做使用相同的 位串
库。
>>>从位串进口BitArray
>>> BitArray(UINT = 0xffffff85,长度= 32).INT
-123L
如果没有外部/内部库,你可以这样做:
int_size = 32
A = 0xffffff85
一个=(一个^ INT('1'* a.bit_length()))+1若a.bit_length()== int_size别的一个
这取2的数 A
,如果 BIT_LENGTH()
数<$ C的补充$ C> A 等于你的 int_size
值。 int_size
值是你把什么作为你的符号二进制数的最高位长度[此处 A
。
假设数字签署的 int_size
位负数将有它的第一个位(符号位)设置为1,因此, BIT_LENGTH
将等于 int_size
。
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); }
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
.
这篇关于2的补十六进制值的签名等同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!