将二进制转换为 ASCII 的Python程序
在本文中,我们将看到Python编程语言中二进制到 ASCII 的转换。有多种方法可以执行此转换,如下所示:
方法一:使用binascii模块
Binascii 有助于在二进制和各种 ASCII 编码的二进制表示之间进行转换。
b2a_uu()函数:这里的“uu”代表“UNIX 到 UNIX 编码”,它负责根据指定的程序将数据从字符串转换为二进制和 ASCII 值。
b2a_uu()函数用于将指定的二进制字符串转换为其对应的 ASCII 等效字符串。
Syntax: b2a_uu(Text)
Parameter: This function accepts a single parameter which is illustrated below:
- Text: This is the specified binary string that is going to be converted into its ASCII equivalent.
Return Values: This function returns the ASCII equivalent.
示例:将二进制转换为 ASCII。
Python3
# Python program to illustrate the
# conversion of Binary to ASCII
# Importing binascii module
import binascii
# Initializing a binary string
Text = b"GFG is a CS Portal"
# Calling the b2a_uu() function to
# Convert the binary string to ascii
Ascii = binascii.b2a_uu(Text)
# Getting the ASCII equivalent
print(Ascii)
Python3
# Python program to illustrate the
# conversion of Binary to ASCII
# Initializing a binary string in the form of
# 0 and 1, with base of 2
binary_int = int("11000010110001001100011", 2);
# Getting the byte number
byte_number = binary_int.bit_length() + 7 // 8
# Getting an array of bytes
binary_array = binary_int.to_bytes(byte_number, "big")
# Converting the array into ASCII text
ascii_text = binary_array.decode()
# Getting the ASCII value
print(ascii_text)
输出:
b"21T9'(&ES(&$@0U,@4&]R=&%L\n"
方法 2:使用内置类型。
这里我们将使用内置类型将二进制转换为 ASCII 值。
首先,调用int(binary_sting, base) ,基数为 2 表示二进制字符串。然后调用int.to_bytes(byte_number, byte_order)函数,其中 byte_order 为“big”,byte_number 为 binary_int 返回字节数组所占用的字节数。这个byte_number 可以通过操作binary_int.bit_length() + 7 // 8 找到。然后调用array.decode 操作将数组转换为ASCII 文本。
示例:将二进制转换为 ASCII
蟒蛇3
# Python program to illustrate the
# conversion of Binary to ASCII
# Initializing a binary string in the form of
# 0 and 1, with base of 2
binary_int = int("11000010110001001100011", 2);
# Getting the byte number
byte_number = binary_int.bit_length() + 7 // 8
# Getting an array of bytes
binary_array = binary_int.to_bytes(byte_number, "big")
# Converting the array into ASCII text
ascii_text = binary_array.decode()
# Getting the ASCII value
print(ascii_text)
输出:
abc