tags:

views:

81

answers:

2

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.

+5  A: 

use the struct module

>>> import struct
>>> struct.pack("l",1024)
'\x00\x04\x00\x00'
>>> struct.pack("l",10240)
'\x00(\x00\x00'
>>> struct.pack("l",900000)
'\xa0\xbb\r\x00'
gnibbler
yes this is right way. thank you for help.
mukul sharma
+1  A: 

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                    ....
Vinko Vrsalovic
Thanks , this is right way what i am looking.
mukul sharma