Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 How to make a bytes object from a list of integers

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

b'\x55\x33\x22 etc.

Thanks

like image 813
Startec Avatar asked Jun 05 '15 04:06

Startec


People also ask

How do you convert int to byte in Python?

An int value can be converted into bytes by using the method int. to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.

How do you encode a byte in Python?

We can use the built-in Bytes class in Python to convert a string to bytes: simply pass the string as the first input of the constructor of the Bytes class and then pass the encoding as the second argument. Printing the object shows a user-friendly textual representation, but the data contained in it is​ in bytes.


1 Answers

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 == '\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
like image 168
abarnert Avatar answered Sep 19 '22 16:09

abarnert