How to concatenate bytes from 3 small ints to make a larger number that is represented by those bytes in Python?

Viewed 91

I have 3 small ints (under 255) which can, therefore, be represented by a single byte.

I would like to create a larger int from that 3 bytes sequence.

For example, if those 3 ints where 1, 2 and 3, I would have:

00000001, 00000010 and 00000011

I then would like to get the int corresponding to:

000000010000001000000011, which according to a calculator would be the integer 66051 when converted to a decimal.

How can I go from 3 small ints to that final larger int in Python?

3 Answers

Bit shift operators?

For your example (1 << 16) + (2 << 8) + 3 gives 66051.

You can repeatedly left-shift a running total before adding another element:

>>> (((1 << 8) + 2) << 8) + 3
66051

This kind of iterated operation can be generalized to any number of integers using functools.reduce:

>>> from itertools import reduce
>>> reduce(lambda acc, x: (acc << 8) + x, [1,2,3]
66051

You can also use the struct module to pack the three 8-bit values into a single bytes value:

>>> import struct
>>> struct.pack('BBB", 1, 2, 3)
b'\x01\x02\x03'

which you can convert to an int value with

>>> int.from_bytes(b'\x01\x02\x03', 'big')
66051

You can use a bit-shift operator on an integer:

a = 0b01
b = 0b10
c = 0b11

d = (a << 16) + (b << 8) + c

print(f"{d:b}")
10000001000000011
Related