Python program to convert a byte string to a list of integers
We have to convert a byte string to a list of integers extracts the byte values (ASCII codes) from the byte string and stores them as integers in a list. For Example, we are having a byte string s=b"Hello" we need to write a program to convert this string to list of integers so the output should be s=[72,101,108,108,111].
Using a Simple list()
Conversion
Byte string is already a sequence of integers (where each byte is an integer between 0 and 255) we can directly convert the byte string to a list of integers using list()
.
# Byte string
s = b"Hello"
# Convert to a list of integers
int_l = list(s)
print(int_l)
Output
[72, 101, 108, 108, 111]
Explanation:
- Variable
s
is a byte string (b"Hello"
) where each character is represented by its corresponding byte value. list(s)
converts the byte string into a list of integers where each byte is represented by its ASCII value:[72, 101, 108, 108, 111]
Using a List Comprehension
We can also use a list comprehension to iterate over the byte string and get a list of integers.
# Byte string
s = b"Hello"
# Convert to a list of integers using list comprehension
int_l = [byte for byte in s]
print(int_l)
Output
[72, 101, 108, 108, 111]
Explanation:
- Variable
s
holds a byte string (b"Hello"
), where each character is represented as a byte (ASCII value). - List comprehension
[byte for byte in s]
iterates over the byte string, converting each byte into its integer value and storing them in the list:[72, 101, 108, 108, 111]
.