Nadim
Nadim

Reputation: 79

Swap pairs of bytes in a hex bytearray in python

Apologies if this has been asked before, I couldn't find what I needed to do in my googling. I have converted a hex string to a bytearray in python, and I want to swap the pairs of bytes round. E.g. 0e d8 AB CD should read d8 0e CD AB. I have tried using byteswap but it doesn't seem to work. Here is the code with which I get the bytearray.

#forward RPM         
    if dirVar.get() == ("Forwards"):
        hexRpm =(hex(RPM.get()))
        forwardRpmFinal = bytearray.fromhex((padhexa(hexRpm)))

padhexa is just a function I'm using to pad the front of the hex bytes with zeros so that the bytearray doesn't throw an error when it encounters a single letter or number.

Thanks in advance!

Upvotes: 0

Views: 352

Answers (1)

zanseb
zanseb

Reputation: 1425

If that what you want to achieve is a endiannes conversion between 2 systems I would suggest you look into the struct package https://docs.python.org/3.7/library/struct.html.

A little example would be:

>>> import struct
>>> var = struct.pack('<h', 5)
>>> var
>>> var = struct.pack('>h', 5)
>>> var

For your data the example would be:

>>> var = struct.pack('<HH', int("d80e", 16), int("cdab", 16))
>>> var
>>> var = struct.pack('>HH', int("d80e", 16), int("cdab", 16))
>>> var

Hope this helps.

Upvotes: 2

Related Questions