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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With