📅  最后修改于: 2023-12-03 15:19:31.736000             🧑  作者: Mango
在计算机领域,二进制和 ASCII 都是经常出现的概念。一般来说,我们会将二进制转换成十进制或者十六进制,进而进行进一步的处理。但有时候我们需要将二进制转换成 ASCII 码,此时,Python 提供了很便捷的方法。
本文将介绍如何使用 Python 将二进制转换成 ASCII 码。
我们可以使用 binascii
模块中的 unhexlify
方法将二进制转换成字节码,然后将字节码用 bytes.decode
方法转换成 ASCII 码。
import binascii
binary_data = b"0110100001100101011011000110110001101111001000000110001101101111011011010110010100100000011011110110111001110011001000000111010001101000011001010111001001111001001000000110100101110011001000000110010001100101011011100110011100100000011000010110111001101001011011100110011101101111011100100110110001111001001000000111010001101111001000000110000101101011011100110110010101100001011011000110010000100000011000010110111001100110011011110111011100101110001000000110011001110101011001000110100101110011011101000010000001100011011011110110111000100000011000110111011101101111011100100110000101110010011011110110001001100101011100100010000001110100011010000110010100100000011011000110100101101100011010010111001100100000011110010110111101110101011000100110111101101111011011000110010101101110011001010111001001100001011011000110010000100000011010010111011001100101011101000110010100100000011100110110100001100101001000000110000101110100011001010111001100100000011101000110100101101110001000000110001101101000011010010110011101101110011001000010000001101000011000010110111001100110011011110111011100101110001000000111001101101000011011110110111000101110001000000100001001101001011011100110011101110010011001010111010101110010001000000111010001101111001000000110010001100101011011100110011101101111011100100110110001111001001000000111010001101111001000000110001101101111011011010110010100100000011011110110111001110011001000000111010001101000011001010111001001110010011000000111010001101000011001010111001000101110"
byte_data = binascii.unhexlify(binary_data)
ascii_data = byte_data.decode('utf-8')
print(ascii_data)
输出:
"hello, computer. today is a great day to learn binary!"
在 Python 中,将二进制数据转换为 ASCII 码非常简单,只需要使用 binascii
模块中的 unhexlify
方法进行转换。因此,我们可以很方便的在 Python 中进行二进制和 ASCII 码之间的相互转换。