Sling Academy
Home/Python/Python: How to Convert a Number to a Byte Array

Python: How to Convert a Number to a Byte Array

Last updated: June 04, 2023

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

# Replace with your number
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

# Replace with your number
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'

Next Article: 2 Ways to Calculate Exponents (Powers) in Python

Previous Article: Python: How to format large numbers with comma separators

Series: Python – Numbers & Math Tutorials

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots