python - 在 python 中打印不需要的字符的代码

标签 python

我正在尝试将作为字符串输入的二进制位流转换为 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/

相关文章:

Python - 迭代 list.append 的结果

Python 编程 - numpy polyfit 说 NAN

python - 使用 RangeSlider 以交互方式更改 Bokeh 中的点图以选择 pandas 数据框中的列

另一个脚本调用脚本时Python导入模块

python - matplotlib 对 x Axis 的值进行分组

python - Pandas Multiindex 数据框删除行

python - 在 Tensorflow 中,我是否需要为 "sinc"或 "gaussian"激活函数添加新的操作?

python - Windows 10 Bash 中的 py-opencv 导入错误

python - 如何基于相同的日期时间 x 轴同时绘制两个不同的数据框列

python - Azure ML 中的属性错误 : 'Logger' object has no attribute 'activity_info' during Dataset Registration