Writing integers in binary to file in python -
how can write integers file in binary in python 3?
for example, want write 6277101735386680763835789423176059013767194773182842284081 file in binary in 24 bytes (unsigned, working positive integers). how can this? tried following:
struct.pack("i", 6277101735386680763835789423176059013767194773182842284081)
this results in
valueerror: cannot fit 'int' index-sized integer
i have tried same other formats ("l", "q"), result in errors:
struct.error: argument out of range
if convert integer 24 bytes, able write file, since know how that. however, can't seem convert integers bytes.
also, how make sure 24 bytes written per integer? writing smaller numbers (1000, 2000, 1598754, 12), should take 24 bytes.
and how can read integers again file afterwards?
with python 3 can following:
i = 6277101735386680763835789423176059013767194773182842284081 open('out.bin', 'wb') file: file.write((i).to_bytes(24, byteorder='big', signed=false)) open('out.bin', 'rb') file: j = int.from_bytes(file.read(), byteorder='big') print(j)
output:
$ python3 tiny.py 6277101735386680763835789423176059013767194773182842284081
Comments
Post a Comment