dzukp
dzukp

Reputation: 191

How to swap two pair bytes in Python 3

I have a bytestring it multiple 4 bytes. Each 4 bytes is a float but for each 4 bytes first two bytes and next two bytes need to be swapped.

example:

input = b'\x00\x00@\xb9a\xa8\xbdf'
struct.unpack('f', b'\x00\x00@\xb9') #-0.00018310546875 is incorrect
struct.unpack('>f', b'\x00\x00@\xb9') #2.3218114255397894e-41 is incorrect
struct.unpack('>f', b'@\xb9\x00\x00') # 5.78125 is correct

How i can easy swap two hi bytes and two low bytes?

Next code is correct

h = b''
for i in range(0, len(input), 4):
    h += struct.pack('BBBB', *(d[i+2],d[i+3],d[i],d[i+1]))
struct.unpack('>ff', h) # is correct (5.78125, -0.05624547600746155)

but may be there are another more easiest way.

Upvotes: 1

Views: 251

Answers (1)

lenik
lenik

Reputation: 23536

This works for me:

>>> a = b'\x12\x34\x56\x78\x9a\xbc\xde\xf0'
>>> ''.join( [chr(a[i^2]) for i in range(len(a))] )
'Vx\x124Þð\x9a¼'
>>> 

You don't even need to use a struct for that.

Upvotes: 1

Related Questions