How to store the data in little endian format in a binary file in Python

863 Views Asked by At

I have a binary file. I want to read hexadecimal data from the terminal in my python code. I am executing the program as follows: python hello.py "2DB6C" "CDEF"

"2DB6C" :- (Address in hex) Indicates GoTo address <2DB6C> in the temp.bin file, where I want to start writing the data.

"CDEF" :- Data to be written in binary file. Remember the data is given in the hex format.

I want to write the data in the small endian format. But it is not working for me.

file = open("temp.bin", "r+b")
file.seek(4)
datatomodify = "CDEF"
data = binascii.unhexlify(datatomodify)
print ("data :", data, "offset addr :", hex(file.tell()))
file.write(data)
print ("after writing addr :", hex(file.tell()))
file.close()

It is writing in the file as "CDEF". But I want to write the data in the little endian format.

Kindly help me in fixing it.

1

There are 1 best solutions below

0
On

You need to use the struct package. Assuming your two numbers are unsigned longs of 4 Bytes:

from struct import *
# data will contain a binary message packed with two Long (4 bytes)
data = pack('<LL', 1, 2)      # < little endian
                              # L first long of value 1
                              # L second long of value 2
# 0100000002000000

And of course you need to convert your hex strings into long numbers. You could reverse the hex strings, but I think it is errorprone.