Editor

Base64 by Hand

#328 · Codes and ciphers · Intermediate · 80 XP · about 18 min

Base64 writes any sequence of bytes using only 64 safe characters, which is how pictures travel inside emails and web pages. Write to_base64(data), where data is a bytes value, that returns its Base64 text as a string. Build it yourself with bit operations, without the base64 module.

The 64 characters, standing for the values 0 to 63 in this order, are:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/

Work through the bytes three at a time. Three bytes make 24 bits: cut them into four groups of 6 bits, starting from the most significant end (the first byte's highest bit), and write the character for the value of each group. At the end there may be one or two bytes left over:

  • two bytes left (16 bits): add two 0 bits on the right to make 18 bits, write the three characters for them, then one =;
  • one byte left (8 bits): add four 0 bits on the right to make 12 bits, write the two characters for them, then ==.

The empty bytes value gives the empty string.

Examples

to_base64(b"Cat")                # returns 'Q2F0'
to_base64(b"Hi")                 # returns 'SGk='
to_base64(b"A")                  # returns 'QQ=='
to_base64(bytes([255, 0, 128]))  # returns '/wCA'

The bytes of b"Cat" are 67, 97 and 116, which is 01000011 01100001 01110100 in binary. Cut into groups of six, that is 010000 110110 000101 110100: the values 16, 54, 5 and 52, which are the characters Q, 2, F and 0.

Constraints

  • data has 0 to 100,000 bytes.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.