我需要将字符串转换为二进制,然后将此二进制数转换为十进制数。我正在做的是询问用户一个单词,将每个字符转换为列表索引,然后将每个索引转换为二进制,向后转换二进制数,并转换为十进制。
没有工作,我也不知道为什么。它说一个字符串没有属性to_bytes
(我不记得我在哪里看到这种语法,我正在寻找一种转换成二进制的方法,然后撤消它,我认为这是在StackOverflow中)。有人能帮我吗?这是代码:
import binascii
senha = list(input("Digite uma frase: "))
senha2 = senha[::-1]
for char in senha2:
char = bin(int.from_bytes(char.encode(), 'big'))
char = char[::-1]
char.to_bytes((char.bit_length() + 7) // 8, 'big').decode()
答案 0 :(得分:1)
我不确定这是否正是你想要的,但这适用于Python3:
In [79]: senha = 'this is my input'
In [80]: senha_bytestring = bytes(senha, 'ascii')
In [81]: senha_bitstring = '0b' + ''.join( [bin(c)[2:] for c in senha_bytestring] )
In [82]: print (senha_bitstring)
0b1110100110100011010011110011100000110100111100111000001101101111100110000011010011101110111000011101011110100
In [83]: senha_dec = int(senha_bitstring, 2)
In [84]: print (senha_dec)
592342518175792645920268465486580
在Python2中没有“字节”类型,但使用ord应该有效:
In [85]: senha = 'this is my input'
In [86]: senha_bytestring = [ ord(c) for c in senha ]
In [87]: senha_bitstring = '0b' + ''.join( [bin(c)[2:] for c in senha_bytestring] )
0b1110100110100011010011110011100000110100111100111000001101101111100110000011010011101110111000011101011110100
In [88]: senha_dec = int(senha_bitstring, 2)
In [89]: print (senha_dec)
592342518175792645920268465486580