bytepack.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/env python
  2. """
  3. Byte packing and unpacking utilities.
  4. Copyright (C) 2017-2020 Cosmin Truta.
  5. Use, modification and distribution are subject to the MIT License.
  6. Please see the accompanying file LICENSE_MIT.txt
  7. """
  8. from __future__ import absolute_import, division, print_function
  9. import struct
  10. def unpack_uint32be(buffer, offset=0):
  11. """Unpack an unsigned int from its 32-bit big-endian representation."""
  12. return struct.unpack(">I", buffer[offset:offset + 4])[0]
  13. def unpack_uint32le(buffer, offset=0):
  14. """Unpack an unsigned int from its 32-bit little-endian representation."""
  15. return struct.unpack("<I", buffer[offset:offset + 4])[0]
  16. def unpack_uint16be(buffer, offset=0):
  17. """Unpack an unsigned int from its 16-bit big-endian representation."""
  18. return struct.unpack(">H", buffer[offset:offset + 2])[0]
  19. def unpack_uint16le(buffer, offset=0):
  20. """Unpack an unsigned int from its 16-bit little-endian representation."""
  21. return struct.unpack("<H", buffer[offset:offset + 2])[0]
  22. def unpack_uint8(buffer, offset=0):
  23. """Unpack an unsigned int from its 8-bit representation."""
  24. return struct.unpack("B", buffer[offset:offset + 1])[0]
  25. if __name__ == "__main__":
  26. # For testing only.
  27. assert unpack_uint32be(b"ABCDEF", 1) == 0x42434445
  28. assert unpack_uint32le(b"ABCDEF", 1) == 0x45444342
  29. assert unpack_uint16be(b"ABCDEF", 1) == 0x4243
  30. assert unpack_uint16le(b"ABCDEF", 1) == 0x4342
  31. assert unpack_uint8(b"ABCDEF", 1) == 0x42