diff --git a/arcadeutils/binary.py b/arcadeutils/binary.py index 7f3789c..e0d141a 100644 --- a/arcadeutils/binary.py +++ b/arcadeutils/binary.py @@ -303,7 +303,22 @@ class ByteUtil: ] return b''.join(chunks) + @staticmethod + def split16bithalves(data: bytes) -> Tuple[bytes, bytes]: + length = len(data) + return( + b''.join(data[x:(x + 2)] for x in range(0, length, 4)), + b''.join(data[(x + 2):(x + 4)] for x in range(0, length, 4)), + ) + @staticmethod def combine8bithalves(upper: bytes, lower: bytes) -> bytes: chunks = [bytes([upper[i], lower[i]]) for i in range(len(upper))] return b''.join(chunks) + + @staticmethod + def split8bithalves(data: bytes) -> Tuple[bytes, bytes]: + return ( + bytes([d for d in data[::2]]), + bytes([d for d in data[1::2]]), + ) diff --git a/tests/test_ByteUtil.py b/tests/test_ByteUtil.py new file mode 100644 index 0000000..079e8e2 --- /dev/null +++ b/tests/test_ByteUtil.py @@ -0,0 +1,41 @@ +from arcadeutils import ByteUtil +import unittest + + +class TestBinaryDiff(unittest.TestCase): + + def test_byteswap(self) -> None: + self.assertEqual( + ByteUtil.byteswap(b"abcd1234"), + b'badc2143', + ) + + def test_wordswap(self) -> None: + self.assertEqual( + ByteUtil.wordswap(b"abcd1234"), + b'dcba4321', + ) + + def test_combine8bithalves(self) -> None: + self.assertEqual( + ByteUtil.combine8bithalves(b"1234", b"abcd"), + b"1a2b3c4d", + ) + + def test_split8bithalves(self) -> None: + self.assertEqual( + ByteUtil.split8bithalves(b"1a2b3c4d"), + (b"1234", b"abcd"), + ) + + def test_combine16bithalves(self) -> None: + self.assertEqual( + ByteUtil.combine16bithalves(b"1234", b"abcd"), + b"12ab34cd", + ) + + def test_split16bithalves(self) -> None: + self.assertEqual( + ByteUtil.split16bithalves(b"1a2b3c4d"), + (b"1a3c", b"2b4d"), + )