📌  相关文章
📜  将字节字符串转换为整数列表的Python程序

📅  最后修改于: 2022-05-13 01:54:46.893000             🧑  作者: Mango

将字节字符串转换为整数列表的Python程序

给定一个字节字符串。任务是编写一个Python程序来将这个字节的字符串转换为一个整数列表。

方法一:使用list()函数

list()函数用于从作为其参数的指定可迭代对象创建列表。

示例: Python程序将一个字节字符串为一个整数列表

Python3
# Python program to illustrate the
# conversion of a byte string
# to a list of integers
  
# Initializing a byte string as GFG
x = b'GFG'
  
# Calling the list() function to
# create a new list of integers that  
# are the ascii values of the byte
# string GFG
print(list(x))


Python3
# Python program to illustrate the
# conversion of a byte string
# to a list of integers
  
# Initializing a byte string
S = "GFG is a CS Portal"
  
nums = []
  
# Calling the for loop to iterate each
# characters of the given byte string
for chr in S:
  
    # Calling the ord() function
    # to convert the specified byte
    # characters to numbers of the unicode
    nums.append(ord(chr))
  
# Printing the unicode of the byte string
print(nums)


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)


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)


输出:

[71, 70, 71]

方法二:使用for循环和ord()函数

ord()函数用于返回表示指定字节字符的 Unicode 代码的数字。

示例: Python程序将一个字节字符串为一个整数列表

蟒蛇3

# Python program to illustrate the
# conversion of a byte string
# to a list of integers
  
# Initializing a byte string
S = "GFG is a CS Portal"
  
nums = []
  
# Calling the for loop to iterate each
# characters of the given byte string
for chr in S:
  
    # Calling the ord() function
    # to convert the specified byte
    # characters to numbers of the unicode
    nums.append(ord(chr))
  
# Printing the unicode of the byte string
print(nums)

输出:

方法 3:通过使用 from_bytes()函数

from_bytes()函数用于将指定的字节字符串转换为其对应的 int 值。

示例: Python程序将一个字节字符串为一个整数列表

蟒蛇3

# 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)

输出:

1

示例 2: Python程序将一个字节字符串为一个整数列表

蟒蛇3

# 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)

输出:

-1024