How to convert bytes to int in Python
Bytes
The data type has a numerical range of 0~255 (0x00~0xFF). A byte has 8 bits of data, that's why its maximum value is 0xFF. In some cases, you need to convert a byte or byte array to an integer for further data processing. Let's see how to convert a byte Bytes
to an integer integer
.
Bytes in Python 2.7Bytes
bytes
There is no built-in data type in Python 2.7 . The keywords byte
are str
equivalent to . We can is
conclude this by the following .
>>> bytes is str
True
bytearray
Used to define a bytes
or an byte array
object.
>>> byteExample1 = bytearray([1])
>>> byteExample1
bytearray(b'\x01')
>>> byteExample2 = bytearray([1,2,3])
>>> byteExample2
bytearray(b'\x01\x02\x03')
Converting bytes to integers in Python 2.7
Python internal module struct
can convert binary data (bytes) to integers. It can convert bytes (actually strings) and integers in Python 2.7 in both directions. Here is a basic introduction to it,
struct.unpack(fmt, string)
# Convert the string according to the given format `fmt` to integers. The result is a tuple even if there is only one item inside.
import struct
testBytes = b"\x00\x01\x00\x02"
testResult = struct.unpack(">HH", testBytes)
print testResult
(1, 2)
The format string >HH
consists of two parts,
-
>
Indicates that binary data isbig-endian
, or in other words, the data is sorted from the high end (most significant bit). For example,\x00\0x1
middle,\x00
is the high byte, and\x01
is the low byte. -
HH
Indicates that there are two objects of type in the byte stringH
.H
Indicates that it isunsigned short
an integer, occupying 2 bytes.
You can get different results from the same string if the data is assigned in a different format.
>>> testResult = struct.unpack('<HH', testBytes)
>>> testResult
(256, 512)
Here, <
indicates that the byte order is little-endian
. Therefore \x00\x01
becomes 00+1*256 = 256
not 0*256+1 = 1
.
>>> testResult = struct.unpack('<BBBB', testBytes)
>>> testResult
(0, 1, 0, 2)
B
indicates the data type unsigned char
, and it occupies 1 byte. Therefore, it \x00\x01\x00\x02
will be converted into 4 unsigned char
values instead of 2 unsigned short
values.
>>> testResult = struct.unpack('<BBB', b'\x00\x01\x00\x02')
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
testResult = struct.unpack('<BBB', b'\x00\x01\x00\x02')
error: unpack requires a string argument of length 3
You can check out struct
the official documentation of the module for more information on format strings.
Bytes in Python 3Bytes
bytes
It is a built-in data type in Python 3, so you can bytes
define bytes directly using the keyword.
>>> testByte = bytes(18)
>>> type(testByte)
<class 'bytes'>
You can also define one or more bytes directly as follows.
>>> testBytes = b'\x01\x21\31\41'
>>> type(testBytes)
<class 'bytes'>
Convert bytes to integers in Python 3
In addition to the module that was introduced in Python 2.7 struct
, you can also use the new Python 3 built-in integer method to perform bytes-to-integer conversion, the int.from_bytes()
method.
int.from_bytes()
example
>>> testBytes = b'\xF1\x10'
>>> int.from_bytes(testBytes, byteorder='big')
61712
This byteorder
option is similar to struct.unpack()
the definition of byte order format.
The byteorder
option is similar to struct.unpack()
format byte order definition.
int.from_bytes()
There is a third option signed
, which assigns an integer type to signed
or unsigned
.
>>> testBytes = b'\xF1\x10'
>>> int.from_bytes(testBytes, byteorder='big', signed=True)
-3824
unsigned chart
Used when the byte is[]
If the data format is unsigned char
and contains only one byte, you can directly access it using the object index to get the integer.
>>> testBytes = b'\xF1\x10'
>>> testBytes[0]
241
>>> testBytes[1]
16
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
How to convert an integer to bytes
Publish Date:2025/05/08 Views:77 Category:Python
-
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 in
How to Remove Punctuation from a String in Python
Publish Date:2025/05/08 Views:190 Category:Python
-
This tutorial discussed methods for removing punctuation from strings in Python. This is a particularly useful step when preprocessing and cleaning text data for NLP. string Remove punctuation from a string in Python using class methods We
How to Convert an Integer to a String in Python
Publish Date:2025/05/08 Views:69 Category:Python
-
This article will show you different ways to convert an integer to a string using Python code, such as str() the function and the f format method. str() Convert integer to string in Python using function We can use the inbuilt function in P
How to Replace Multiple Characters in a String in Python
Publish Date:2025/05/08 Views:97 Category:Python
-
This tutorial showed you how to replace multiple characters in a string in Python. Suppose we want to remove special characters from a string and replace them with spaces. The list of special characters to remove is !#$%^*() . Additionally,
How to remove the last character from a string in Python
Publish Date:2025/05/08 Views:141 Category:Python
-
A Python string is a combination of characters enclosed in double or single quotes. Python provides multiple functions to manipulate strings. This article will show you different ways to remove the last character and specific characters fro
How to Remove a Substring from a String in Python
Publish Date:2025/05/08 Views:182 Category:Python
-
This tutorial explains how to delete a substring in a string in Python. It will show you that strings cannot just be deleted, but only replaced. This tutorial also lists some sample codes to clarify the concepts, as the method has changed c
Get parent directory in Python
Publish Date:2025/05/08 Views:109 Category:Python
-
This tutorial will explain various ways to get the parent directory of a path in Python. A parent directory is a directory above or above a given directory or file. For example, C:\folder\subfolder\myfile.txt the parent directory of the pat
Catching keyboard interrupt errors in Python
Publish Date:2025/05/08 Views:106 Category:Python
-
The error occurs when a user manually tries to stop a running program using Ctrl + C or Ctrl + , or in the case of Jupyter Notebook by interrupting the kernel . To prevent accidental use of , which often occurs , we can use exception handli
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