Method – 4 : using struct module

In this approach, we will use the unpack() method present in the struct module in Python. It is pre-installed so we don’t need to install it externally using pip, just import it and use it.

Syntax of unpack() method –

struct.unpack(β€˜<β€˜ or β€˜>’ +’B’ or β€˜b’ * len(byte_string) , variable_name/byte_string)

Explanation of each parameter –

β€˜<β€˜ or β€˜>’ : Here we will use β€˜<β€˜ to denote Little-endian and β€˜>’ to denote Big-endian.

β€˜B’ or β€˜b’ * len(byte_string) : β€˜B’ represents unsigned bytes, whereas β€˜b’ represents signed bytes, we need to take care of this β€˜bytes’ as if we pass an unsigned byte value in the next parameter and use the signed byte here then it will not give the desired output. In case of len(byte_string) we can either pass a variable which holds the byte string or pass the byte string in-place.

variable_name / byte_string : Here we will either pass the variable in which we have the byte string stored or directly pass the byte string.

Code – 

Python3




import struct
 
# Storing the byte string
bstr = b"GFG is a CS Portal"
 
# using the unpack method of struct
# and passing required values
# here we are Multiplying B with len(bstr)
# and concatenating it with '<' to tell
# that we want to convert a certain length of
# byte string into into list of itnegers using Big-endian
# and the bytes are signed
data_ints = struct.unpack('<' + 'b'*len(bstr), bstr)
 
# Printing the result
print(data_ints)


Output

(71, 70, 71, 32, 105, 115, 32, 97, 32, 67, 83, 32, 80, 111, 114, 116, 97, 108)

Time Complexity – O(n) # n denotes the length of byte string

Auxiliary Space – O(n) # n denotes the length of the unpacked integers list



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