Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

python - Base64 to string of 1s and 0s convertor

I did some search for this question, but I can not find relevant answer. I am trying to convert some string form input() function to Base64 and from Base64 to raw string of 1s and 0s. My converter is working, but its output are not the raw bits, but something like this: b'YWhvag=='. Unfortunately, I need string of 1s and 0s, because I want to send this data via "flickering" of LED.

Can you help me figure it out please? Thank you for any kind of help!

import base64

some_text = input()

base64_string = (base64.b64encode(some_text.encode("ascii")))

print(base64_string)
question from:https://stackoverflow.com/questions/65937902/base64-to-string-of-1s-and-0s-convertor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I have understood it corretly you want binary equivalent of string like 'hello' to ['1101000', '1100101', '1101100', '1101100', '1101111'] each for h e l l o

import base64

some_text = input('enter a string to be encoded(8 bit encoding): ')


def encode(text):
    base64_string = (base64.b64encode(text.encode("ascii")))
    return ''.join([bin(i)[2:].zfill(8) for i in base64_string])

def decode(binary_digit):
    b = str(binary_digit)
    c = ['0b'+b[i:i+8] for i in range(0,len(b), 8)]
    c = ''.join([chr(eval(i)) for i in c])
    return base64.b64decode(c).decode('ascii')

encoded_value = encode(some_text)
decoded_value = decode(encoded_value)

print(f'encoded value of {some_text} in 8 bit encoding is: {encoded_value}')
print(f'decoded value of {encoded_value} is: {decoded_value}')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...