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

2024-06-16 11:50:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将字符串转换为二进制,但我认为我没有正确使用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'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
The Binary value of 'r' is b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
The Binary value of 'u' is b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
The Binary value of 'n' is b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
The Binary value of 'o' is b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

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


Tags: ofthe字符串代码nameinimportfor
1条回答
网友
1楼 · 发布于 2024-06-16 11:50:31

如果你要找的是画笔,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

this question 了解更多详细信息,以及其他一些方法。其中一些方法确实使用 binascii,除非你被迫使用binascii,否则我会再次敦促你 你不用担心

相关问题 更多 >