How to make a bytes object from a list of integers in Python 3

Question:

I have an array of integers (all less than 255) that correspond to byte values, e.g. [55, 33, 22]. How can I turn that into a bytes object that would look like b'x55x33x22'?

Asked By: Startec

||

Answers:

struct.pack("b"*len(my_list), *my_list)

I think will work

>>> my_list = [55, 33, 22]
>>> struct.pack("b"*len(my_list), *my_list)
b'7!x16'

If you want hex, you need to make it hex in the list

>>> my_list = [0x55, 0x33, 0x22]
>>> struct.pack("b"*len(my_list), *my_list)
b'U3"'

In all cases, if that value has an ASCII representation, it will display it when you try to print it or look at it.

Answered By: Joran Beasley

The bytes constructor takes an iterable of integers, so just feed your list to that:

l = list(range(0, 256, 23))
print(l)
b = bytes(l)
print(b)

Output:

[0, 23, 46, 69, 92, 115, 138, 161, 184, 207, 230, 253]
b'x00x17.E\sx8axa1xb8xcfxe6xfd'

See also: Python 3 – on converting from ints to ‘bytes’ and then concatenating them (for serial transmission)

Answered By: Kevin J. Chase

Just call the bytes constructor.

As the docs say:

… constructor arguments are interpreted as for bytearray().

And if you follow that link:

If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

So:

>>> list_of_values = [55, 33, 22]
>>> bytes_of_values = bytes(list_of_values)
>>> bytes_of_values
b'7!x16'
>>> bytes_of_values == b'x37x21x16'
True

Of course the values aren’t going to be x55x33x22, because x means hexadecimal, and the decimal values 55, 33, 22 are the hexadecimal values 37, 21, 16. But if you had the hexadecimal values 55, 33, 22, you’d get exactly the output you want:

>>> list_of_values = [0x55, 0x33, 0x22]
>>> bytes_of_values = bytes(list_of_values)
>>> bytes_of_values == b'x55x33x22'
True
>>> bytes_of_values
b'U3"'
Answered By: abarnert
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.