I have some bytes
.
b'\x01\x02\x03'
And an int
in range 0..255.
5
Now I want to append the int
to the bytes
like this:
b'\x01\x02\x03\x05'
How to do it? There is no append
method in bytes
. I don't even know how to make the integer become a single byte.
>>> bytes(5) b'\x00\x00\x00\x00\x00'
To concatenate multiple byte arrays, you can use the Bytes. concat() method, which can take any number of arrays.
The easiest way to do what you want is a + a[:1] . You could also do a + bytes([a[0]]) . There is no shortcut for creating a single-element bytes object; you have to either use a slice or make a length-one sequence of that byte.
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.
Let us see how to write bytes to a file in Python. First, open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.
bytes
is immutable. Use bytearray
.
xs = bytearray(b'\x01\x02\x03') xs.append(5)
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