DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' def bits_to_base64(bitstr): """ >>> bits_to_base64('010001110100100001100111') 'R0hn' >>> bits_to_base64('010101000110010101110011') 'VGVz' >>> bits_to_base64('01001101') 'TQ==' >>> bits_to_base64('0100110101100001') 'TWE=' >>> s = '100111010110100101010011010111100111011110001110110101110011000011' >>> result = bits_to_base64(s) >>> result 'nWlTXneO1zD' >>> s2 = '10110101100010110011010101010110111100011101101011100101' >>> result2 = bits_to_base64(s2) >>> result2 'tYs1VvHa5Q==' """ b64str = '' ending = '' # Check if bitstr length is multiple of 6 and handle cases where it isn't. # Since bitstr length will be a multiple of 8 (a byte), there are three # cases: # 1. len(bitstr) % 6 == 0 when total bytes is a multiple of 3. # 2. len(bitstr) % 6 == 2 when total bytes % 3 is 1. # 3. len(bitstr) % 6 == 4 when total bytes % 3 is 2. # Cases 2 and 3 require special handling. if len(bitstr) % 6 == 2: ending = '==' # pad base64 string with == bitstr += '0000' # make bitstr length a muliple of 6 elif len(bitstr) % 6 == 4: ending = '=' # pad base64 string with = bitstr += '00' # make bitstr length a muliple of 6 # Convert each 6 bits to a base64 encoded byte for i in range(0, len(bitstr), 6): b64str += DIGITS[int(bitstr[i:i+6], 2)] return b64str + ending if __name__ == '__main__': import doctest doctest.testmod()