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) |
(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.
Contact Us