How do I write a long integer as binary in Python?

I think for unsigned integers (and ignoring endianness) something like

import binascii

def binify(x):
    h = hex(x)[2:].rstrip('L')
    return binascii.unhexlify('0'*(32-len(h))+h)

>>> for i in 0, 1, 2**128-1:
...     print i, repr(binify(i))
... 
0 '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1 '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01'
340282366920938463463374607431768211455 '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'

might technically satisfy the requirements of having non-Python-specific output, not using an explicit mask, and (I assume) not using any non-standard modules. Not particularly elegant, though.


Two possible solutions:

  1. Just pickle your long integer. This will write the integer in a special format which allows it to be read again, if this is all you want.

  2. Use the second code snippet in this answer to convert the long int to a big endian string (which can be easily changed to little endian if you prefer), and write this string to your file.

The problem is that the internal representation of bigints does not directly include the binary data you ask for.


The PyPi bitarray module in combination with the builtin bin() function seems like a good combination for a solution that is simple and flexible.

bytes = bitarray(bin(my_long)[2:]).tobytes()

The endianness can be controlled with a few more lines of code. You'll have to evaluate the efficiency.