Base64 Encoding Explained

Technology / Thursday, November 16th, 2017

If you ever attempt to send pure binary data in an email, chances are that the data will end up mishandled since email is designed to handle text data or printable characters. This is a more generic problem and email is just one common case of it.

To solve this issue, binary data is changed to text data by means of mapping it to printable characters. In computer speak this transformation is called encoding. Emphatically note that this is not encryption (That is a topic for another day).

A popular and simple algorithm for encoding is Base64. The 64 in the name refers to the fact that this encoding scheme uses 64 symbols to map from binary data to text.

Here is a table with the most common mapping used.

Value Char Value Char Value Char Value Char
0 A 16 Q 32 g 48 w
1 B 17 R 33 h 49 x
2 C 18 S 34 i 50 y
3 D 19 T 35 j 51 z
4 E 20 U 36 k 52 0
5 F 21 V 37 l 53 1
6 G 22 W 38 m 54 2
7 H 23 X 39 n 55 3
8 I 24 Y 40 o 56 4
9 J 25 Z 41 p 57 5
10 K 26 a 42 q 58 6
11 L 27 b 43 r 59 7
12 M 28 c 44 s 60 8
13 N 29 d 45 t 61 9
14 O 30 e 46 u 62 +
15 P 31 f 47 v 63 /

The binary input bits are read from left to right in chunks of 3 bytes (24 bits). This chunk is then divided into 4 chunks of 6 bits each. Each of the 6 bit chunk is mapped to the Base64 value. Note that since we are using only 64 symbols, 6 bits is sufficient to map to all the values uniquely (2^6 = 64).

At the receiving end the entire process is applied in reverse and voila you have your original binary data intact.

One caveat – what happens if at the end of your data you have less than 24 bits to split and map ? Well in this case you add something called as padding, enough 0 bits are added to fill in the missing bits. The padding is represented by “=” character. The padding bits are discarded during decoding.

Now that you have a basic idea of Base64 encoding, you could code it up or you can save yourself the trouble and use it from widely available libraries. In Java for example the class Base64.Encoder can be found in the java.util package.

Go forth and encode.

One Reply to “Base64 Encoding Explained”

Leave a Reply

Your email address will not be published. Required fields are marked *