0

I'm looking for a loop similar to this for converting ASCII to decimal then decimal to binary string: string = input("Enter message: ")

#Convert string from ASCII to Decimal
A_string = [ord(c) for c in string]
print(A_string)

# add 1 to ASCII value 
B_string = A_string
for i in range(len(B_string)):
    B_string[i] = B_string[i] + 1 
print(B_string)


#Decimal to Binary
decimal = B_string
remainder = decimal
Binary_string = decimal

for i in range(len(decimal)):
    remainder[i] = int(decimal[i])
    remainder[i] %= 2
    decimal[i] = decimal[i] // 2
    Binary_string[i] = str(remainder[i] + Binary_string[i])
print(Binary_string)

What I'm NOT looking for are things like this:

res = "".join(f"{ord(shiftedChar):08b}")

shiftedChar

I'm looking for BASIC OLD SCHOOL techniques... programming what's actually happening using basic division, multiplication, powers, etc

2

1 Answer 1

0

From https://stackoverflow.com/a/7397195/1675501

First, you need to strip the 0b prefix, and left-zero-pad the string so it's length is divisible by 8, to make dividing the bitstring up into characters easy:

bitstring = bitstring[2:]
bitstring = -len(bitstring) % 8 * '0' + bitstring

Then you divide the string up into blocks of eight binary digits, convert them to ASCII characters, and join them back into a string:

string_blocks = (bitstring[i:i+8] for i in range(0, len(bitstring), 8))
string = ''.join(chr(int(char, 2)) for char in string_blocks)

If you actually want to treat it as a number, you still have to account for the fact that the leftmost character will be at most seven digits long if you want to go left-to-right instead of right-to-left.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.