ilanschnell/bitarray

Byte-order swap on data type level

postlund opened this issue · 2 comments

I have a bitbuffer containing audio samples (signed 16 bit) which are stored in big endian, but I need them in little endian. Currently I iterate over the array two bytes at the time and swap values, but this seems rather ineffcient. Would it be possible to add a function that does this without having to pass between native code and python all the time? Something like:

import bitarray
data = b"\x01\x02\x03\04"
swapped = bitarray.swap_endian(data, 2)
print(swapped) => b"\x02\x01\x04\x03"

Second argument (2) would be the number of bytes to swap.

Thank you for using bitarray! The Python standard library module array has a method for swapping the byte-order. The following code does what you want:

import array
data = b"\x01\x02\x03\04"
a = array.array('H')  # H: unsigned short = 2 bytes
a.frombytes(data)
a.byteswap()
swapped = a.tobytes()
print(swapped)

Ah, thank you, that is exactly what I need! Thank you for an awesome project nonetheless! 👍