diff --git a/src/bitstruct/__init__.py b/src/bitstruct/__init__.py index efb4dda..a333dd0 100644 --- a/src/bitstruct/__init__.py +++ b/src/bitstruct/__init__.py @@ -676,6 +676,14 @@ def byteswap(fmt, data, offset=0): return data_swapped.getvalue() +def bytereverse(data): + """Reverse bits in `data` bytes. For example, the bytes ``\\x11\\x22`` + will produce the result ``\\x88\\x44`` + + """ + return pack('<' + 'u8' * len(data), *data) + + def compile(fmt, names=None, text_encoding='utf-8', diff --git a/tests/test_bitstruct.py b/tests/test_bitstruct.py index 9504488..34ce6d0 100644 --- a/tests/test_bitstruct.py +++ b/tests/test_bitstruct.py @@ -277,6 +277,15 @@ def test_byteswap(self): unpacked = unpack('u1u5u2u16', byteswap('12', packed)) self.assertEqual(unpacked, (1, 2, 3, 1024)) + def test_bytereverse(self): + """Byte reverse. + + """ + ref = b'\x11\x22\x33\xFF\x00\x80\x7F' + res = b'\x88\x44\xCC\xFF\x00\x01\xFE' + + self.assertEqual(bytereverse(ref), res) + def test_endianness(self): """Test pack/unpack with endianness information in the format string.