Converting binary representation to signed 64 bit integer in Python

DonutGaz

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.

wim

Try the bitstring module:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Convert binary to signed, little endian 16bit integer in Python

How to convert and Integer to an 64-bit byte representation in python

converting integer into 4 bit binary

Converting from an integer to its binary representation

Converting hexstr to signed integer - Python

Converting integer to binary in python

Converting an Integer to Binary in Python

Negative integer to signed 32-bit binary

Signed binary representation in C

How to implement a recursive method for converting an integer to binary representation

Converting an integer to signed 2's complement binary string

Decode a byte array to a signed integer up to 64 bit

Why the literal "-9223372036854775808" (min 64 bit signed integer) is not accepted by kotlin?

Print a signed 64-bit integer in hexadecimal and octal

Python converting binary data to 64-bit floating point. "error: unpack requires a buffer of 4 bytes"

bit shifting signed integer

Counting the binary representation of an Integer

Cast a 10 bit unsigned integer to a signed integer in python

Python: Find longest binary gap in binary representation of an integer number

Python 3.6 converting 8 bit binary to decimal

Converting 32-bit binary string with Integer.parseInt fails

How to put 32-bit signed integer into higher 32 bits of 64-bit unsigned integer?

Convert 32-bit signed integer to 64-bit integer while preserving the exact bits

C/C++ Converting a 64 bit integer to char array

Converting an ip address to binary representation

Python converting from base64 to binary

Bit operations converting to an integer

18-bit Signed Binary number to Decimal in Python

Convert two 32 bit integers to one signed 64 bit integer string