Base64 - what, why, and how

When you have anything that varies, and you want to have a standard agreement, then you have to have some sort of a convention. This is the case with encoding data.

Things like email are sent as ASCII and can't handle binary data, so the binary data needs to be converted into text.

ASCII uses 128 unique values (0–127), so that is 7 bits. Most computer systems organise data in 8 bit bytes, so we can see there is a need to distinguish which is being used.

"Binary to text encoding" is converting non-text based things (images, video, et al) to plain text (ASCII). So the bits of a binary file (image, video, for example) are converted into a sequence of ASCII characters.

It is possible to send binary data, however, because it is binary there is a chance that the bits of the binary file could be misinterpreted to be something else (tcp/ip type stuff) and cause a kerfuffle.

Data URI

There are some useful things you can do with this conversion. Say you want to embed an image in an html file (which I did once for a holding page) and don't have access to any assets, you could embed the image in your HTML. You could also store an image or small video into a NoSQL database. To embed data you can use a Data URI. It's in this format:

data:[<mimetype>][;base64],<data>

You will need the MIME type of the binary file you want to embed. I found this full list of mime types which is really handy.

You can use the btoa JavaScript function to convert binary to ASCII, and then atob to convert ASCII to binary.

Resources