Python 3.8 - 使用 binascii.a2b_uu 将字符串转换为二进制文件



我试图将字符串转换为二进制,但我认为我没有正确使用binascii。波纹管是我的代码:

import binascii
name = 'Bruno'
for c in name:
print ("The Binary value of '" + c +"' is", binascii.a2b_uu(c))

结果不是我预期的,如下所示:

The Binary value of 'B' is b'x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00'
The Binary value of 'r' is b'x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00'
The Binary value of 'u' is b'x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00'
The Binary value of 'n' is b'x00x00x00x00x00x00x00x00x00x00x00x00x00x00'
The Binary value of 'o' is b'x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00'

我需要更改什么才能获得 0 和 1 中的二进制值?

如果你要找的是画笔,binascii是大锤。这 完全不是您要做的事情的工具。你可以得到 使用ord函数的字符的代码点,并且每隔这么多 将整数转换为二进制的方法。这里有一种方法可以做到这一点:

def ascii_name(name):
for c in name:
print("The binary value of {} is {:08b}".format(c, ord(c)))
ascii_name("Bruno")

带输出

The binary value of B is 01000010
The binary value of r is 01110010
The binary value of u is 01110101
The binary value of n is 01101110
The binary value of o is 01101111

看到这里 问题 以获取更多详细信息和其他一些方法。其中一些方法确实使用 binascii,尽管除非你被迫使用binascii,否则我会再次敦促 你不用担心。

最新更新