Skip to content

number_encoding_utils

encode_number(number)

Encodes a number to a sequence of bytes.

Parameters:

Name Type Description Default
number int

The number to encode.

required

Returns:

Name Type Description
bytes bytes

The encoded sequence of bytes.

Source code in src/eolib/data/number_encoding_utils.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def encode_number(number: int) -> bytes:
    """
    Encodes a number to a sequence of bytes.

    Args:
        number (int): The number to encode.

    Returns:
        bytes: The encoded sequence of bytes.
    """
    value = number
    d = 0xFE
    if number >= THREE_MAX:
        d = value // THREE_MAX + 1
        value = value % THREE_MAX

    c = 0xFE
    if number >= SHORT_MAX:
        c = value // SHORT_MAX + 1
        value = value % SHORT_MAX

    b = 0xFE
    if number >= CHAR_MAX:
        b = value // CHAR_MAX + 1
        value = value % CHAR_MAX

    a = value + 1

    return bytes([a, b, c, d])

decode_number(encoded_number)

Decodes a number from a sequence of bytes.

Parameters:

Name Type Description Default
encoded_number bytes

The sequence of bytes to decode.

required

Returns:

Name Type Description
int int

The decoded number.

Source code in src/eolib/data/number_encoding_utils.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def decode_number(encoded_number: bytes) -> int:
    """
    Decodes a number from a sequence of bytes.

    Args:
        encoded_number (bytes): The sequence of bytes to decode.

    Returns:
        int: The decoded number.
    """
    result = 0
    length = min(len(encoded_number), 4)

    for i in range(length):
        value = encoded_number[i]

        if value == 0xFE:
            break

        value -= 1

        if i == 0:
            result += value
        elif i == 1:
            result += CHAR_MAX * value
        elif i == 2:
            result += SHORT_MAX * value
        elif i == 3:
            result += THREE_MAX * value

    return result