Search code examples
pythonarraysendianness

python hex payload into bytearray and convert endianness


Hello i am searching for a way to decode a hex coded sensor payload.

The payload is payload_hex = "11154c1789870005bd0005bd01000200002900" i convert it into an bytearray using.

byte = bytearray.fromhex(payload)
decoded = {}
decoded["byte_7"]=byte[7]
decoded["byte_8"]=byte[8]
print(decoded)

i am getting for byte_7 = 5 and byte_8 = 189 as a result but that is false the correct numbers would be byte_7 = 1280 and byte_8 = 189. The problem is the endianess. the hex 05 should be 1280 and the hex bd schould be 189.

enter image description here

Could anyone give me a hint how to make it work in python?

Thanks in advance!


Solution

  • Byte 7 can't be 1280, because one byte can only hold numbers from 0 to 255. Hex 05 is just 5, not 1280. Hex 0500, however, is 1280.

    You should put the two bytes together like 05bd, which is done with shifting and ORing:

    >>> 0x05 << 8 | 0xbd
    1469
    >>> hex(0x05 << 8 | 0xbd)
    '0x5bd'