• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#  Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
2#
3#  Licensed under the Apache License, Version 2.0 (the "License");
4#  you may not use this file except in compliance with the License.
5#  You may obtain a copy of the License at
6#
7#      https://www.apache.org/licenses/LICENSE-2.0
8#
9#  Unless required by applicable law or agreed to in writing, software
10#  distributed under the License is distributed on an "AS IS" BASIS,
11#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12#  See the License for the specific language governing permissions and
13#  limitations under the License.
14
15"""Data transformation functions.
16
17From bytes to a number, number to bytes, etc.
18"""
19
20import math
21
22
23def bytes2int(raw_bytes: bytes) -> int:
24    r"""Converts a list of bytes or an 8-bit string to an integer.
25
26    When using unicode strings, encode it to some encoding like UTF8 first.
27
28    >>> (((128 * 256) + 64) * 256) + 15
29    8405007
30    >>> bytes2int(b'\x80@\x0f')
31    8405007
32
33    """
34    return int.from_bytes(raw_bytes, 'big', signed=False)
35
36
37def int2bytes(number: int, fill_size: int = 0) -> bytes:
38    """
39    Convert an unsigned integer to bytes (big-endian)::
40
41    Does not preserve leading zeros if you don't specify a fill size.
42
43    :param number:
44        Integer value
45    :param fill_size:
46        If the optional fill size is given the length of the resulting
47        byte string is expected to be the fill size and will be padded
48        with prefix zero bytes to satisfy that length.
49    :returns:
50        Raw bytes (base-256 representation).
51    :raises:
52        ``OverflowError`` when fill_size is given and the number takes up more
53        bytes than fit into the block. This requires the ``overflow``
54        argument to this function to be set to ``False`` otherwise, no
55        error will be raised.
56    """
57
58    if number < 0:
59        raise ValueError("Number must be an unsigned integer: %d" % number)
60
61    bytes_required = max(1, math.ceil(number.bit_length() / 8))
62
63    if fill_size > 0:
64        return number.to_bytes(fill_size, 'big')
65
66    return number.to_bytes(bytes_required, 'big')
67
68
69if __name__ == '__main__':
70    import doctest
71
72    doctest.testmod()
73