1

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()
2
  • Well formatted question but do not forget to add tags. They can really decrease answer time. Commented Sep 13, 2014 at 11:24
  • It's not very clear what you want to do. Can you give a small example string and the output you expect? Does this do what you want? s='A String'; print int(s.encode('hex'), 16) Commented Sep 13, 2014 at 13:24

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.