Search code examples
pythoncsigned

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 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); }

Solution

  • 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.