Debian Codegraph @

compat/libpng/contrib/pngexif/bytepack.py

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