Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
_binary.py114 linesDownload Raw Back to PIL
1#
2# The Python Imaging Library.
3# $Id$
4#
5# Binary input/output support routines.
6#
7# Copyright (c) 1997-2003 by Secret Labs AB
8# Copyright (c) 1995-2003 by Fredrik Lundh
9# Copyright (c) 2012 by Brian Crowell
10#
11# See the README file for information on usage and redistribution.
12#
13
14
15"""Binary input/output support routines."""
16
17from __future__ import annotations
18
19from struct import pack, unpack_from
20
21
22def i8(c: bytes) -> int:
23    return c[0]
24
25
26def o8(i: int) -> bytes:
27    return bytes((i & 255,))
28
29
30# Input, le = little endian, be = big endian
31def i16le(c: bytes, o: int = 0) -> int:
32    """
33    Converts a 2-bytes (16 bits) string to an unsigned integer.
34
35    :param c: string containing bytes to convert
36    :param o: offset of bytes to convert in string
37    """
38    return unpack_from("<H", c, o)[0]
39
40
41def si16le(c: bytes, o: int = 0) -> int:
42    """
43    Converts a 2-bytes (16 bits) string to a signed integer.
44
45    :param c: string containing bytes to convert
46    :param o: offset of bytes to convert in string
47    """
48    return unpack_from("<h", c, o)[0]
49
50
51def si16be(c: bytes, o: int = 0) -> int:
52    """
53    Converts a 2-bytes (16 bits) string to a signed integer, big endian.
54
55    :param c: string containing bytes to convert
56    :param o: offset of bytes to convert in string
57    """
58    return unpack_from(">h", c, o)[0]
59
60
61def i32le(c: bytes, o: int = 0) -> int:
62    """
63    Converts a 4-bytes (32 bits) string to an unsigned integer.
64
65    :param c: string containing bytes to convert
66    :param o: offset of bytes to convert in string
67    """
68    return unpack_from("<I", c, o)[0]
69
70
71def si32le(c: bytes, o: int = 0) -> int:
72    """
73    Converts a 4-bytes (32 bits) string to a signed integer.
74
75    :param c: string containing bytes to convert
76    :param o: offset of bytes to convert in string
77    """
78    return unpack_from("<i", c, o)[0]
79
80
81def si32be(c: bytes, o: int = 0) -> int:
82    """
83    Converts a 4-bytes (32 bits) string to a signed integer, big endian.
84
85    :param c: string containing bytes to convert
86    :param o: offset of bytes to convert in string
87    """
88    return unpack_from(">i", c, o)[0]
89
90
91def i16be(c: bytes, o: int = 0) -> int:
92    return unpack_from(">H", c, o)[0]
93
94
95def i32be(c: bytes, o: int = 0) -> int:
96    return unpack_from(">I", c, o)[0]
97
98
99# Output, le = little endian, be = big endian
100def o16le(i: int) -> bytes:
101    return pack("<H", i)
102
103
104def o32le(i: int) -> bytes:
105    return pack("<I", i)
106
107
108def o16be(i: int) -> bytes:
109    return pack(">H", i)
110
111
112def o32be(i: int) -> bytes:
113    return pack(">I", i)
114 
codekingpro/portable-devtools · Team Ai