Skip to content Skip to sidebar Skip to footer

Signed Equivalent Of A 2's Complement Hex Value

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 si

Solution 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 = 32a = 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.

Post a Comment for "Signed Equivalent Of A 2's Complement Hex Value"