I have a hex file which appears as below:-
00000000 AA AA 11 FF EC FF E7 3E FA DA D8 78 39 75 89 4E
00000010 FD FD BF E5 FF DD FF AA E9 78 67 84 90 E4 87 83
00000020 9F E7 80 FD FE 73 75 78 93 47 58 93 EE 33 33 3F
I want to read 3rd and 4th byte. Swap these two bytes and save them in a variable. For e.g, i want to save 0xFF11 (after byteswap) in variable "num"
This is what i tried: I read these two bytes one by one
data=open('xyz.bin','rb').read()
num1=data[2]
num2=data[3]
num1,num2=num2,num1
num= num1*100+num2
print(num)
Now the problem is num variable has integer value and i have no idea how to get hex into it. I am stuck here and not able to proceed further. Any help would be welcomed.
PS: I am very new to python.
import struct
with open("xyz.bin", "rb") as f:
f.seek(2)
num, = struct.unpack("<H", f.read(2))
print "little endian:", hex(num), num # little endian: 0xff11 65297
In Python 3, you could create an integer directly from bytes:
with open('xyz.bin','rb') as file:
file.seek(2)
num = int.from_bytes(file.read(2), 'little')
print(hex(num), num) # -> 0xff11 65297
First, you would have to multiply num1
by 256
, of course, not 100
(you could write decimal 256
as 0x100
, though, if that helps make your intention clearer).
Second, to format an integer as a hex number, use
print("{:x}".format(num))
For example:
>>> num1 = 0xff
>>> num2 = 0xab
>>> num = num1*256 + num2
>>> print("{:x}".format(num))
ffab
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With