我正在try 将作为字符串输入的二进制位流转换为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),其中base为2表示二进制字符串.然后调用int.to_bytes(byte_number,byte_order)函数,其中byte_order表示"大",byte_number表示二进制_int返回字节数组所占用的字节数.这个字节号可以通过二进制_int.bit_length()+7//8操作找到.然后调用array.解码操作将数组转换为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中两个矩阵的自定义Hadamard风格产物

合并同名列,但一列为空,另一列包含值

如何在不使用字符串的情况下将namedtuple属性传递给方法?

Polars Dataframe:如何按组删除交替行?

模型序列化器中未调用现场验证器

Python -根据另一个数据框中的列编辑和替换数据框中的列值

计算相同形状的两个张量的SSE损失

如何在BeautifulSoup中链接Find()方法并处理无?

无法使用requests或Selenium抓取一个href链接

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

pandas在第1列的id,第2列的标题,第3列的值,第3列的值?

使用Python从URL下载Excel文件

UNIQUE约束失败:customuser. username

我的字符串搜索算法的平均时间复杂度和最坏时间复杂度是多少?

从列表中获取n个元素,其中list [i][0]== value''

Python避免mypy在相互引用中从另一个类重定义类时失败

如何在Python中使用Iscolc迭代器实现观察者模式?

在numpy数组中寻找楼梯状 struct

Python—在嵌套列表中添加相同索引的元素,然后计算平均值

如何使用matplotlib查看并列直方图