Reputation: 183
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?
Upvotes: 0
Views: 285
Reputation: 1447
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.
Upvotes: 1