Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append to bytes in python 3

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' 
like image 209
felixbade Avatar asked Nov 18 '14 18:11

felixbade


People also ask

How do you append byte?

To concatenate multiple byte arrays, you can use the Bytes. concat() method, which can take any number of arrays.

How do you concatenate bytes in Python 3?

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.

How do you input 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.

How do you write bytes in Python?

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.


1 Answers

bytes is immutable. Use bytearray.

xs = bytearray(b'\x01\x02\x03') xs.append(5) 
like image 151
simonzack Avatar answered Sep 27 '22 21:09

simonzack