3

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.

2 Answers 2

13

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'
Sign up to request clarification or add additional context in comments.

Comments

4

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                    ....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.