Read multiple bytes in Hexadecimal file using python

user3469616 picture user3469616 · Mar 27, 2014 · Viewed 19.3k times · Source

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.

Answer

Simon Pantzare picture Simon Pantzare · Mar 27, 2014
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