Question

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.

Was it helpful?

Solution 3

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

OTHER TIPS

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

You may be interested in some/all of the following operations which abstract away all of the bitwise math that you'd otherwise have to do.

import struct

line = '00000000 AA AA 11 FF EC FF E7 3E FA DA D8 78 39 75 89 4E'.split()

bytearray(int(x,16) for x in line[3:5])
Out[42]: bytearray(b'\x11\xff')

struct.unpack('H',bytearray(int(x,16) for x in line[3:5]))
Out[43]: (65297,) 

hex(65297)
Out[44]: '0xff11'

packed_line = bytearray(int(x,16) for x in line[1:])

struct.unpack('{}H'.format(len(packed_line)/2),packed_line)
Out[47]: (43690, 65297, 65516, 16103, 56058, 30936, 30009, 20105)

The Best way of doing it is by using struct module.enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top