Python Bytes

What to do with bytes

Sarper Makas
2 min readAug 17, 2023
Microsoft Designer

In Python, a byte is a fundamental unit of data that represents a sequence of binary data. Bytes are often used to handle raw binary data, such as reading and writing files and more.

They are also used for representing characters in various character encodings, such as UTF-8.

Creating Bytes

You can create bytes using the bytes() constructor or by using a byte literal prefix b.

# Creating bytes from a string
data_str = "Hello, World!"
data_bytes = bytes(data_str, encoding='utf-8')
print(data_bytes)

# Using byte literal prefix
data_bytes = b"Hello, Bytes!"
print(data_bytes)

Accessing Bytes

Bytes are an immutable sequence of integers, each representing a byte of data. You can make individual bytes using indexing and slicing, just like with strings.

data_bytes = b"Hello, Bytes!"
print(data_bytes[0]) # Accessing the first byte
print(data_bytes[7:12]) # Slicing bytes

Bytes and Strings

Converting Bytes to String

You can convert bytes to strings using the decode() method.

data_bytes = b"Hello, Bytes!"
data_str = data_bytes.decode('utf-8')
print(data_str)

Converting String to Bytes

You can convert strings to bytes using the encode() method.

data_str = "Hello, World!"
data_bytes = data_str.encode('utf-8')
print(data_bytes)

Bytes and Integers

Converting Int to Byte

To create a byte representation of an integer in Python, you can use the to_bytes() method.

This method allows you to specify the number of bytes the integer should be represented in, as well as the byte order (big-endian or little-endian).

# Create a byte representation of an integer
integer_value = 12345
num_bytes = 2 # Number of bytes for the representation

# Convert integer to bytes (big-endian)
byte_representation = integer_value.to_bytes(num_bytes, byteorder='big')

print(byte_representation)

Converting Byte to Int

You can convert a byte representation back to an integer using the int.from_bytes() method.

# Convert byte representation back to integer
byte_representation = b'\x30\x39'
integer_value = int.from_bytes(byte_representation, byteorder='big')

print(integer_value)

Working with Files

Bytes are commonly used for reading and writing binary files.

# Reading a binary file
with open('file.bin', 'rb') as f:
data = f.read()
print(data)

# Writing to a binary file
data = b"This is binary data."
with open('output.bin', 'wb') as f:
f.write(data)

--

--