0

So I'm trying to create a program that takes the individual ascii values of characters in a string of user input, adds 1, and converts that new number to binary.

for example, if the user inputs "abcde" I need the output to be

1100010 1100011 1100100 1100101 1100110

with the binary values separated by spaces like that. Now, what I have so far is

text = input()
for ch in text:
    new = ord(ch) + 1

    decimal = new
    bitString = ''
    while decimal > 0:
        remainder = decimal % 2
        decimal = decimal // 2
        bitString = str(remainder) + bitString

print(bitString)

which gives me the binary for the last character input (so if the user inputs "abcde" it gives the binary of the ascii value plus 1), but how can I make it do it for all the characters?

1 Answer 1

1

You need to declare bitstring as an empty string before the for loop starts, outside of it. Otherwise, it gets emptied every time the loop runs and that's why only the last value is printed. You could use the bin function as well instead of ord, which would immediately give you a binary representation.

Sign up to request clarification or add additional context in comments.

2 Comments

okay, so I put bitString outside the for loop, now the output it's giving me is 11001101100101110010011000111100010. how do I get the binary values to be separated by spaces?
Add a space to the bitString obviously... And then when you print it there'll be a space

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.