我正在尝试将作为字符串输入的二进制位流转换为 ascii。这是相同的代码
# 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)
在 (Python v3.6.2) 中它给出输出 abc
但在 google colab 中我得到这个输出 ���������������� ����abc
这就是我构建逻辑的方式。首先,调用 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 文本。
我不明白为什么会这样。任何人都可以帮助我如何在 google colab 中获得正确的输出。或者,如果有人可以向我展示任何其他方式来进行转换,那将非常有帮助。
最佳答案
除法先于加法:
byte_number = binary_int.bit_length() + 7 // 8
等于
byte_number = binary_int.bit_length() + 0
参见 python operator precedence .
您缺少括号以正确排序您的数学计算:
binary_int = int("11000010110001001100011", 2);
# calculate amount of bytes in the given number, rounded up to
# full bytes if fewer then 8 full bits remain
byte_number = (binary_int.bit_length() + 7) // 8 # fixed
# 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
关于python - 在 python 中打印不需要的字符的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71736046/