xref: /aosp_15_r20/external/libpng/contrib/pngexif/bytepack.py (revision a67afe4df73cf47866eedc69947994b8ff839aba)
1#!/usr/bin/env python
2
3"""
4Byte packing and unpacking utilities.
5
6Copyright (C) 2017-2020 Cosmin Truta.
7
8Use, modification and distribution are subject to the MIT License.
9Please see the accompanying file LICENSE_MIT.txt
10"""
11
12from __future__ import absolute_import, division, print_function
13
14import struct
15
16
17def 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
22def 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
27def 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
32def 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
37def 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
42if __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
49