By using from_bytes() function

The from_bytes() function is used to convert the specified byte string into its corresponding int values.

Syntax:

int.from_bytes(bytes, byteorder, *, signed=False)

Parameters: This function accepts some parameters which are illustrated below:

  • bytes: A byte object
  • byteorder: This parameter determines the order of representation of the integer value. byteorder can have values as either “little” where most significant bit is stored at the end and least at the beginning, or big, where MSB is stored at start and LSB at the end. Big byte order calculates the value of an integer in base 256.
  • signed: Its default value is False. This parameter Indicates whether to represent 2’s complement of a number.

Return values: This function returns an int equivalent to the given byte.

Example: Python program to a byte string to a list of integers

Python3




# Python program to illustrate the
# conversion of a byte string
# to a list of integers
 
# Initializing byte value
byte_val = b'\x00\x01'
 
# Converting to int
# byteorder is big where MSB is at start
int_val = int.from_bytes(byte_val, "big")
 
# Printing int equivalent
print(int_val)


Output:

1

Example 2: Python program to a byte string to a list of integers

Python3




# Python program to illustrate the
# conversion of a byte string
# to a list of integers
 
# Initializing a byte string
byte_val = b'\xfc\x00'
 
# 2's complement is enabled in big
# endian byte order format
int_val = int.from_bytes(byte_val, "big", signed="True")
 
# Printing int object
print(int_val)


Output:

-1024

The time and space complexity of all the methods is same::

Time Complexity: O(n)

Auxiliary Space: O(n)

Python program to convert a byte string to a list of integers

Given a byte string. The task is to write a Python program to convert this byte of string to a list of integers. 

Similar Reads

Method 1: By using list() function

The list() function is used to create a list from the specified iterable taken as its parameter....

Method 2: By using for loop and ord() function

...

Method 3: By using from_bytes() function

The ord() function is used to return the number representing the Unicode code of a specified byte character....

Method – 4 : using struct module

...

Contact Us