Python: How to Convert a Number to a Byte Array

This step-by-step article will show you how to convert numbers (both integers and floats) to byte arrays in Python. We will make use of the `struct` module to get the job done. The module provides functions to convert between Python values and C-style data types, including byte arrays.

Using the struct module to convert a number to a byte array

The step-by-step process

Step 1: Import the `struct` module.

``import struct``

Step 2: Convert the number to a byte array using the appropriate format specifier:

• For integers, you can use the `pack()` function with format specifiers like â€˜bâ€™ (signed char), â€˜Bâ€™ (unsigned char), â€˜hâ€™ (short), â€˜Hâ€™ (unsigned short), â€˜iâ€™ (int), â€˜Iâ€™ (unsigned int), â€˜qâ€™ (long long), â€˜Qâ€™ (unsigned long long), depending on the desired size and signedness of the integer.
• For floats, you can use the `pack()` function with format specifiers like â€˜fâ€™ (float) or â€˜dâ€™ (double).

Step 3: Use the `pack()` function to convert the number to a byte array:

``````number = 2024
byte_array = struct.pack('i', number)
# Replace 'i' with the appropriate format specifier``````

The `byte_array` variable now contains the byte representation of the number. You can access individual bytes or perform other operations on the byte array as needed.

Complete examples

In the code snippet below, the input is an integer:

``````import struct

number = 2024

# Replace 'i' with the appropriate format specifier
byte_array = struct.pack('i', number)

print(byte_array)``````

Output:

``b'\xe8\x07\x00\x00'``

Another example (now the input is a float):

``````import struct

number = -1.2345

# Replace 'i' with the appropriate format specifier
byte_array = struct.pack('f', number)

print(byte_array)``````

Output:

``b'\x19\x04\x9e\xbf'``

Why donâ€™t simply use the to_bytes() method?

The `to_bytes()` method does not work with floats. It only works with integers. If your use case doesnâ€™t involve floats, then you can use this method, but it requires specifying the length and the byte order of the output.

Example:

``````# an integer
input = 2023

# convert to a big-endian 4-byte array
b = input.to_bytes(4, 'big')

print(b)``````

Output:

``b'\x00\x00\x07\xe7'``

Search tutorials, examples, and resources