How to convert an integer to bytes
Converting an integer int
to a byte bytes
is the inverse of bytes
converting a byte to an integer . Most of the to methods int
described in this article are the inverse of the to methods.int
bytes
bytes
int
Generic method for converting int
to in Python 2.7 and 3bytes
You can use the struct function in the Python module pack
to convert integers to bytes in a specific format.
>>> import struct
>>> struct.pack("B", 2)
'\x02'
>>> struct.pack(">H", 2)
'\x00\x02'
>>> struct.pack("<H", 2)
'\x02\x00'
struct.pack
The first argument in the function is the format string, which specifies the byte format such as length, byte order (little/big endian), etc.
New conversion method from int
to introduced in Python 3bytes
Use bytes
to convert int
tobytes
As mentioned in the previous article, bytes
it is a built-in data type in Python 3. You can bytes
easily convert integers 0 to 255 to byte data types using .
>>> bytes([2])
b'\x02'
int.to_bytes()
Convert integer to byte type by
A new integer class method was introduced in Python 3.1 int.to_bytes()
. It is the reverse conversion method discussed in the previous article int.from_bytes()
.
>>> (258).to_bytes(2, byteorder="little")
b'\x02\x01'
>>> (258).to_bytes(2, byteorder="big")
b'\x01\x02'
>>> (258).to_bytes(4, byteorder="little", signed=True)
b'\x02\x01\x00\x00'
>>> (-258).to_bytes(4, byteorder="little", signed=True)
b'\xfe\xfe\xff\xff'
The first argument is the length of the converted byte data, the second argument byteorder
defines the byte order as little or big-endian, and the optional argument signed
determines whether to use two's complement to represent integers.
Running speed comparison
In Python 3, you have three ways to convert int
to bytes
,
-
bytes()
method -
struct.pack()
method -
int.to_bytes()
method
We will measure the execution time of each method to compare their performance, and finally provide suggestions for making the program run faster.
>>> import timeint
>>> timeit.timeit('bytes([255])', number=1000000)
0.31296982169325455
>>> timeit.timeit('struct.pack("B", 255)', setup='import struct', number=1000000)
0.2640925447800839
>>> timeit.timeit('(255).to_bytes(1, byteorder="little")', number=1000000)
0.5622947660224895
Conversion Method | Execution time (1 million times) |
---|---|
bytes() |
0.31296982169325455 s |
struct.pack() |
0.2640925447800839 s |
int.to_bytes() |
0.5622947660224895 s |
Therefore, use struct.pack()
the function execute to perform integer-to-byte conversion for best performance, although it has been introduced in Python 2, old still has its uses!
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Implementing a Low-Pass Filter in Python
Publish Date:2025/05/07 Views:90 Category:Python
-
Low pass filter is a term in signal processing basics and is often used to filter signals to obtain more accurate results. This tutorial will discuss the low-pass filter and how to create and implement it in Python. A low-pass filter is use
Implementing Curl command in Python using requests module
Publish Date:2025/05/07 Views:98 Category:Python
-
requests This article will discuss and implement different curl commands using the module in Python . requests Installing modules in Python Python provides us with requests the module to execute curl command. Install it in Python 3 using Pi
Using fetchall() in Python to extract elements from a database
Publish Date:2025/05/07 Views:173 Category:Python
-
This article aims to describe fetchall() the working methods of extracting elements from a database using and how to display them correctly. This article will also discuss list(cursor) how functions can be used in programs. fetchall() Extra
Parsing log files in Python
Publish Date:2025/05/07 Views:106 Category:Python
-
Log files contain information about events that occurred during the operation of a software system or application. These events include errors, requests made by users, bugs, etc. Developers can further scan these usage details to find poten
Declaring a variable without a value in Python
Publish Date:2025/05/07 Views:58 Category:Python
-
A variable is a reserved memory location that can store some value. In other words, variables in a Python program provide data to the computer to process operations. Every value in Python has a data type. There are numbers, lists, tuples, e
Defining class global variables in Python
Publish Date:2025/05/07 Views:81 Category:Python
-
A global variable is a variable that is visible and available in every part of the program. Global variables are also not defined in any function or method. On the other hand, local variables are defined in functions and can be used only in
Incrementing loop step by 2 in Python
Publish Date:2025/05/07 Views:199 Category:Python
-
In each iteration, for the loop increases the counter variable by a constant. A loop with the sequence 0, 2, 4, 6 for will increase the counter variable by 2 each iteration. This article will show you some for ways to increment by 2 in a lo
Pool map with multiple parameters in Python
Publish Date:2025/05/07 Views:105 Category:Python
-
multiprocessing This article will explain different ways to perform parallel function execution using the module in Python . multiprocessing The module provides functionality to perform parallel function execution using multiple inputs and
Python if...else in Lambda function
Publish Date:2025/05/07 Views:68 Category:Python
-
lambda Functions are used to implement some simple logic in Python and can be thought of as anonymous functions. It can have multiple parameters but only one expression, just def like any other function defined using the keyword. We can def