Python Bytes: Create and Convert Binary Data

Creating or converting bytes in Python starts with matching the input to the representation you need. The bytes() constructor creates an immutable sequence of byte values, and text needs an encoding such as UTF-8.

I’ll show how to encode text with UTF-8 and represent an integer with an explicit length and byte order.

TL;DR

Use bytes for immutable binary data, but choose its input form carefully: a size creates zero bytes, while text needs an encoding such as UTF-8. For a number’s binary representation, choose an explicit integer serialization format.

  • Encode text with UTF-8 when you need its bytes.
  • Use integer iterables for explicit byte values from 0 through 255.
  • Use bytearray when values must change in place.

What Are Python Bytes?

A bytes object is an immutable sequence of integers from 0 through 255. Its values represent binary data.

Python’s built-in bytes constructor accepts no argument, an integer size, an iterable of byte values, or text alongside an encoding.

The object behaves as a sequence: it supports indexing, slicing, membership tests, and comparison with another bytes object. Indexing returns an integer, while a slice returns another bytes object. Its immutability makes a value safe to pass around without another part of the program changing its contents unexpectedly.

How to Create and Convert Bytes Step by Step

Start with the kind of data already in your program. I ran a named Python file for the text conversion path, and it showed five encoded bytes for café.

1. Create empty bytes or a fixed size

Calling bytes with no arguments returns an empty object.

print(bytes())
print(bytes(3))
b''
b'\x00\x00\x00'

The integer means a length here, not a number to serialize. This form is useful for a known-size buffer, though code that needs to fill the buffer should usually use a mutable bytearray.

2. Build bytes from integer values

Pass an iterable of integers when each item fits from 0 through 255.

print(bytes([65, 66, 67]))
b'ABC'

Values outside that range raise ValueError. This constructor does not encode the decimal spelling of each integer, so use a text encoding when the goal is to represent written digits.

3. Encode text and decode it back

Call the string encoding method with UTF-8. I ran python3 bytes_demo.py and got these values:

b'caf\xc3\xa9'
5
b'\x00\x00\x00'
b'ABC'
café
Terminal showing Python bytes demo command and its five output lines
The command output shows the encoded bytes, their length, a zero-filled value, integer values, and decoded text.

The accented character uses two UTF-8 bytes, so the encoded length is five. Decode with UTF-8 to recover the text. Python documents these text encoding and decoding methods.

4. Represent an integer as bytes

Integer serialization needs a chosen storage length and byte order. For example, the integer 258 fits in two unsigned bytes, with a different order when the least significant byte comes first.

print((258).to_bytes(2, byteorder='big'))
print((258).to_bytes(2, byteorder='little'))
b'\x01\x02'
b'\x02\x01'
print((258).to_bytes(1, byteorder='big'))
OverflowError: int too big to convert

The chosen length must hold the value, and signed integers need a signed representation. For records with several fields, Python’s struct module defines packing and unpacking layouts.

5. Combine bytes or edit them

Concatenation creates a new bytes object. For many pieces, joining them in one operation avoids repeatedly creating intermediate results.

parts = [b'Py', b'thon']
print(b''.join(parts))
data = bytearray(b'cat')
data[0] = ord('b')
print(data)
b'Python'
bytearray(b'bat')

A bytearray allows item assignment and can be converted back to bytes when editing is complete. The binary sequence documentation covers the operations shared by these types.

Common Bytes() Mistakes and Edge Cases

This table pairs common bytes errors with their symptoms and fixes.

CaseSymptomFix
Text without an encodingTypeError: string argument without an encodingEncode the string with UTF-8 or pass the encoding to the constructor.
Integer passed as a valueThe result contains that many zero bytesUse integer serialization with an explicit length and byte order.
Iterable value outside 0–255ValueError during constructionValidate or transform each value into the byte range first.
Too-small integer storage lengthOverflowError during serializationChoose enough bytes for the value and its signedness.
Character count used as encoded sizeNon-ASCII text occupies more bytes than charactersMeasure the encoded result rather than the source string.
Attempt to assign into bytesTypeError because the sequence is immutableUse bytearray while editing, then convert if immutable data is needed.

I reproduced the missing-encoding error with a text input. The exact error was TypeError: string argument without an encoding. This occurs when text is passed without its encoding.

Truth-value tests treat an empty bytes object as false and a non-empty one as true.

Boolean operations such as and and or return one of their operands rather than converting both operands into Boolean values. Comparisons work lexicographically by byte value, so their result describes byte order rather than text equivalence.

Python numeric types have their own conversion rules. A float needs a representation format to define its byte layout. For a protocol-defined numeric layout, use its documented struct format.

Conclusion

Match the constructor to the source type, then check the resulting values or length before passing binary data onward. This compact decision table keeps the distinct input forms separate.

Starting dataUseResult
No databytes()Empty immutable sequence
Required buffer lengthbytes(n)n zero bytes
Existing byte valuesbytes(iterable)Validated values from 0 through 255
Texttext.encode(‘utf-8’)Encoded bytes
Integer or structured recordint.to_bytes() or structDefined binary representation

For the exact behavior, consult the Python bytes reference and the AskPython guides to bytearray and string and bytes conversion. Those sources help choose a representation that matches the next operation.

FAQ

These answers address common questions about creating and using byte sequences.

How do you initialize bytes in Python?

Use bytes() for an empty object, bytes(n) for n zero bytes, or bytes(iterable) for byte values. Encode text with a named encoding such as UTF-8.

How do you add bytes in Python?

Use + to concatenate a small number of bytes objects or b”.join(parts) for multiple pieces. Use bytearray when contents must change.

How many bytes is a character in Python?

A str character has no fixed byte size. The encoded length depends on the text and encoding, so measure the encoded result.

Does bytes(n) serialize an integer?

No. It creates n zero bytes. Use integer serialization with an explicit length and byte order to represent the numeric value.

Vijaykrishna Ram
Vijaykrishna Ram
Articles: 99