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.
You need to use the struct package. Assuming your two numbers are unsigned longs of 4 Bytes:
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.