Endianess - hex to dec little endian. uncorrect data types

Viewed 166

I converted hex to dec, but it turned out to be in big endian and I need little endian (ex. 1500 = 21 instead 5376 which I get). I tried to use struct function but I get some problem:

u16ModuleID_hex = str(f3.read(4))
ba = bytearray.fromhex(u16ModuleID_hex)
ba.reverse()
u16ModuleID_dec = struct.unpack("<h", ba)

Error: non-hexadecimal number found in fromhex() arg at position 1 So, I added: ba = bytearray.fromhex(u16ModuleID_hex[0][2:]) Error: struct.error: unpack requires a buffer of 2 bytes

u16ModuleID_hex is for example b'10b5'. I assume it's sth with the b' in front and overall with data types.

2 Answers

need little endian (ex. 1500 = 21 instead 5376 which I get)

Take look at int.frombytes (requires python3.2 or newer)

data = b'\x15\x00'
print(int.from_bytes(data, "big"))
print(int.from_bytes(data, "little"))

output

5376
21

Just .pack() and .unpack() your data to flip endianess:

import struct

a = 0x1500

print(a)
# --> 5376

b, = struct.unpack("<h", struct.pack(">h", a))
print(b)
# --> 21
Related