JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

How to convert bytes to int in Python

Author:JIYIK Last Updated:2025/05/05 Views:

BytesThe 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 Bytesto an integer integer.


Bytes in Python 2.7Bytes

bytesThere is no built-in data type in Python 2.7 . The keywords byteare strequivalent to . We can isconclude this by the following .

>>> bytes is str
True

bytearrayUsed to define a bytesor an byte arrayobject.

>>> 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 structcan 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 >HHconsists of two parts,

  1. >Indicates that binary data is big-endian, or in other words, the data is sorted from the high end (most significant bit). For example, \x00\0x1middle, \x00is the high byte, and \x01is the low byte.
  2. HHIndicates that there are two objects of type in the byte string H. HIndicates that it is unsigned shortan 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\x01becomes 00+1*256 = 256not 0*256+1 = 1.

>>> testResult = struct.unpack('<BBBB', testBytes)
>>> testResult
(0, 1, 0, 2)

Bindicates the data type unsigned char, and it occupies 1 byte. Therefore, it \x00\x01\x00\x02will be converted into 4 unsigned charvalues ​​instead of 2 unsigned shortvalues.

>>> 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 structthe official documentation of the module for more information on format strings.


Bytes in Python 3Bytes

bytesIt is a built-in data type in Python 3, so you can bytesdefine 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 byteorderoption is similar to struct.unpack()the definition of byte order format.

The byteorderoption is similar to struct.unpack()format byte order definition.

int.from_bytes()There is a third option signed, which assigns an integer type to signedor unsigned.

>>> testBytes = b'\xF1\x10'
>>> int.from_bytes(testBytes, byteorder='big', signed=True)
-3824

unsigned chartUsed when the byte is[]

If the data format is unsigned charand 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.

Article URL:

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

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial