pythonbit-manipulation

Converting binary representation to signed 64 bit integer in Python


Against the advice of online resources, I'm using Python to do some simple bit shifting in one of my scripts. The bit shifting is fine, it's representing the result that's difficult. Let me explain.

I have a 64 bit binary representation

1000010101010111010101010101010101010101010101010111010101010101

which, when represented as a signed integer, should be negative. However, Python defaults to type long, preventing the number from being signed by the first bit, yielding the number 9608242155010487637.

How can I get Python to recognize the sign bit in 64 bits?

To clarify, I'm using Python 2.7.


Solution

  • Try the bitstring module:

    >>> from bitstring import BitArray
    >>> s = '1000010101010111010101010101010101010101010101010111010101010101'
    >>> BitArray(bin=s).int
    -8838501918699063979