Skip to content
July 2, 2011 / oop123

Useless Stuff: Base64 Encoding

Base64 encoding is an encoding scheme used to encode binary data into characters for situations in which binary data may not be appropriate (e.g. network transmission). It uses an alphabet of 64 safe characters (“safe” means universal and unlikely to be corrupted during use) to encode every 6 bits of binary data.

Binary Data in Decimal Character
0 – 25 A – Z
26 – 51 a – z
52 – 61 0 – 9
62 +
63 /

Example: using base64 to encode “Hello!”

  1. “Hello!” ‘s ASCII code is (72, 101, 108, 108, 111, 33)
  2. (72, 101, 108, 108, 111, 33) in binary is (01001000, 01100101, 01101100, 01101100, 01101111, 00100001)
  3. (01001000, 01100101, 01101100, 01101100, 01101111, 00100001) is divided into groups of 6 bits
    (010010, 000110, 010101, 101100, 011011, 000110, 111100, 100001)
  4. (010010, 000110, 010101, 101100, 011011, 000110, 111100, 100001) in decimal is (18, 6, 21, 44, 27, 6, 60, 33)
  5. (18, 6, 21, 44, 27, 6, 60, 33) is translated with the above table into “SGVsbG8h”

Note that if you leave the “!” out of “Hello!”, you will only have 40 bits to be divided into groups of 6, with 4 bits left over. These 4 bits are 1111 which is encoded into ‘P’ (001111). A “=” will then need to be appended to the end of the encoded string to indicate ‘P’ was encoded with 4 bits instead of 6 bits (“==” would indicate 2 bits). The final encoded string is “SGVsbGP=”. Note that some variants of base64 do not require “==” or “=” to be appended since the length of the encoded string can be used to find the number of bytes used in the encoding.

In Java, you can use the Apache Common Codec's Base64 class to encode and decode base64 data.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: