简体   繁体   中英

Convert string to binary, and binary to decimal in Python?

I need to convert a string into binary, and then convert this binary number into decimal. What I was doing was ask the user for a word, transform each character into a list index, and then convert each index into binary, turn backwards the binary number, and convert into decimal.

Didn't work, and I don't know why. It says that a string has no attribute to_bytes (I don't remember where I saw this syntax, I was searching for a way to convert into binary, and undo it, I think was here in StackOverflow). Can someone help me? Here's the code:

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()

I'm not sure if this is exactly what you want, but this works in 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

In Python2 there is no 'bytes' type, but using ord should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM