How to store an arbitrarily long int in a binary file in python?
The pickle builtin can do this if you pass protocol version 2 ("new binary protocol"):
import pickle
pickle.dumps(2**10000, 2)
Returns a string of 1259 bytes. Of course you want to write it to a file normally, so usepickle.dump(2**10000, file, 2)
a source to share
It is not clear to me if you are generally asking how to store large integers in a binary file or if the number 2 ** 10000 is significant. If it's important, then using more than a kilobyte for storage is obviously very wasteful (I can write it in 8 characters each!)
I'll take the general case for myself, but first you'll need 10001 bits to store 2 ** 10000, not 10000, so the question is what to do with the extra 7 bits needed to send to the byte boundary in the file. I'm just going to store it in 10008 bits (1251 bytes). This solution uses the bitstring module .
from bitstring import BitArray
fout = open('bignumber', 'wb')
a = BitArray(uint=2**10000, length=10008)
a.tofile(fout)
and to read it back:
the_number = BitArray(filename='bignumber').uint
It really just saves the number and nothing else in the file.
a source to share