dejv_IT
dejv_IT

Reputation: 63

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)

Upvotes: 1

Views: 252

Answers (1)

Epsi95
Epsi95

Reputation: 9047

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}')

Upvotes: 1

Related Questions