Home > Software design >  Little to big endian buffer at once python
Little to big endian buffer at once python

Time:10-06

I've created a buffer of words represented in little endian(Assuming each word is 2 bytes):

A000B000FF0A

I've separated the buffer to 3 words(2 bytes each)

A000
B000
FF0A

and after that converted to big endian representation:

00A0
00B0
0AFF

Is there a way instead of split into words to represent the buffer in big endian at once? Code:

buffer='A000B000FF0A'
for i in range(0, len(buffer), 4):
    value = endian(int(buffer[i:i   4], 16))

def endian(num):
    p = '{{:0{}X}}'.format(4)
    hex = p.format(num)
    bin = bytearray.fromhex(hex).reverse()
    l = ''.join(format(x, '02x') for x in bin)
    return int(l, 16)

CodePudding user response:

Using the struct or array libraries are probably the easiest ways to do this.

Converting the hex string to bytes first is needed.

Here is an example of how it could be done:

from array import array
import struct

hex_str = 'A000B000FF0A'
raw_data = bytes.fromhex(hex_str)
print("orig string:      ", hex_str.casefold())
# With array lib
arr = array('h')
arr.frombytes(raw_data)
# arr = array('h', [160, 176, 2815])
arr.byteswap()
array_str = arr.tobytes().hex()
print(f"Swap using array: ", array_str)

# With struct lib
arr2 = [x[0] for x in struct.iter_unpack('<h', raw_data)]
# arr2 = [160, 176, 2815]
struct_str = struct.pack(f'>{len(arr2) * "h"}', *arr2).hex()
print("Swap using struct:", struct_str)

Gives transcript:

orig string:       a000b000ff0a
Swap using array:  00a000b00aff
Swap using struct: 00a000b00aff

CodePudding user response:

You can use the struct to interpret your bytes as big or little endian. Then you can use the hex() method of the bytearray object to have a nice string representation.

Docs for struct.

import struct

# little endian
a = struct.pack("<HHH",0xA000,0xB000,0xFF0A) 

# bih endian
b = struct.pack(">HHH",0xA000,0xB000,0xFF0A) 

print(a)
print(b)

# convert back to string
print( a.hex()  )
print( b.hex() )

Which gives:

b'\x00\xa0\x00\xb0\n\xff'
b'\xa0\x00\xb0\x00\xff\n'
00a000b00aff
a000b000ff0a
  • Related