29

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'\x55\x33\x22'?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Startec
  • 12,496
  • 23
  • 93
  • 160

3 Answers3

37

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'\x37\x21\x16'
True

Of course the values aren't going to be \x55\x33\x22, 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'\x55\x33\x22'
True
>>> bytes_of_values
b'U3"'
wjandrea
  • 28,235
  • 9
  • 60
  • 81
abarnert
  • 354,177
  • 51
  • 601
  • 671
  • nice but could you please explain why "b'7!\x16'" is equal to '\x37\x21\x16'? – totalMongot Jan 07 '22 at 20:30
  • 2
    @totalMongot the ASCII value for 0x37 is "7" (digit 7) and the ASCII value for 0x21 is "!" (exclamation point). The ASCII value for 0x16 is SYN (control character synchronous idle). Since SYN is a non-printing character, it is represented in a bytes object by the hex escape \x16 – James Duvall Sep 22 '22 at 18:47
  • @totalMongot There was a typo where that was written as a string (`'\x37\x21\x16'`) instead of bytes (`b'\x37\x21\x16'`), if that's what confused you. I fixed it. – wjandrea Jan 02 '23 at 16:25
10

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'\x00\x17.E\\s\x8a\xa1\xb8\xcf\xe6\xfd'

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

Kevin J. Chase
  • 3,856
  • 4
  • 21
  • 43
0
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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179