mukul sharma
mukul sharma

Reputation: 177

how to write integer number in particular no of bytes in python ( file writing)

assume i have to store few integer numbers like 1024 or 512 or 10240 or 900000 in a file, but the condition is that i can consume only 4 bytes (not less nor max).but while writing a python file using write method it stored as "1024" or "512" or "10240" ie they written as ascii value but i want to store directly their binary value.

Any help will really appreciable.

Upvotes: 3

Views: 8550

Answers (2)

John La Rooy
John La Rooy

Reputation: 304473

use the struct module

>>> import struct
>>> struct.pack("i",1024)
'\x00\x04\x00\x00'
>>> struct.pack("i",10240)
'\x00(\x00\x00'
>>> struct.pack("i",900000)
'\xa0\xbb\r\x00'

In Python3, it you can use the to_bytes method of int. The paren around 1024 are only necessary as 1024. parses as a float and would cause a syntax error.

>>> (1024).to_bytes(4, "big")
b'\x00\x00\x04\x00'
>>> (1024).to_bytes(4, "little")
b'\x00\x04\x00\x00'

Upvotes: 13

Vinko Vrsalovic
Vinko Vrsalovic

Reputation: 340486

The struct module will do

>>> import struct
>>> f = open('binary.bin','wb')
>>> f.write(struct.pack("l",1024))
>>> f.close()

vinko@parrot:~$ xxd -b binary.bin
0000000: 00000000 00000100 00000000 00000000                    ....

Upvotes: 4

Related Questions