I decided to make my own Base64 encoder and decoder, despite there already being a module for this in the standard library. It's just meant to be a fun project. However, the encoder, for some reason, incorrectly encodes some characters, and I haven't had luck with debugging. I've tried to follow the model found on Wikipedia to a tee. I believe the problem has to do with the underlying conversion to binary format, but I'm not sure.
Code:
def encode_base64(data):
raw_bits = ''.join('0' + bin(i)[2:] for i in data)
# First bit is usually (always??) 0 in ascii characters
split_by_six = [raw_bits[i: i + 6] for i in range(0, len(raw_bits), 6)]
if len(split_by_six[-1]) < 6: # Add extra zeroes if necessary
split_by_six[-1] = split_by_six[-1] + ((6 - len(split_by_six[-1])) * '0')
padding = 2 if len(split_by_six) % 2 == 0 else 1
if len(split_by_six) % 4 == 0: # See if padding is necessary
padding = 0
indexer = ([chr(i) for i in range(65, 91)] # Base64 Table
+ [chr(i) for i in range(97, 123)]
+ [chr(i) for i in range(48, 58)]
+ ['+', '/'])
return ''.join(indexer[int(i, base=2)] for i in split_by_six) + ('=' * padding)
When I run the following sample code, I get the incorrect value, and you can see below:
print(base_64(b'any carnal pleasure'))
# OUTPUT: YW55QMbC5NzC2IHBsZWFzdXJl=
# What I should be outputting: YW55IGNhcm5hbCBwbGVhc3VyZS4=
For some odd reason, the first few characters are correct, and then the rest aren't. I am happy to answer any questions!