Thursday, February 9, 2012

Base 64 Encoding

When?
If you need to store binary data in a string/text, you could use Base 64 encoding.

What is the problem with storing bytes as such?
Every byte contains 2^8 (256) possible values. But some of these values cannot be represented as text.

Why is it called base 64?
Now, if we think of the usual characters that can be represented as text, they would be A-Z, a-z and 0-9. That gives us 26+26+10 = 62 characters. Let's take 2 more like + and - (or /) and make this 64. Why 64 instead of 62? Since 64 is a round figure. Err, not in the decimal (base 10) system. But, in the binary (base 2) system.
2^6 = 64
So, now in this base 64 system, each of these 64 characters can be represented in 6-bits.

Note: If 8-bits can be called octets, let us call these 6-bits as hexets for now. I just made that up.
Googling for it, I find here that hexet is also, in German, a second-person plural subjunctive I of hexen, which has to deal with magic!

How can I convert an octet sequence into a hexet sequence?
Consider a byte sequence such as "Man". In terms of bytes, the values are 77, 97 and 110.
In terms of bits, these can be represent as 01001101 01100001 01101110
Now, if progress thru this sequence in hexets, we get
010011 010110 000101 101110
which is 19, 22, 5 and 46
which translates to TWFu
considering A-Z as 0-25, a-z as 26-51, and so on.

What if my byte sequence is not divisable by 3?
We pad zeroes at the end of the sequence to make it so. Also, we could introduce ending characters such as = to make up for missing characters.

Any issues with it?
Well, since each 3 octets translate into 4 hexets, it does increase the size of your byte sequence by 33%.

Is this being used anywhere?
The ASP.NET ViewState is one such place that comes to mind.

Can you tell me more?
It's all here. http://en.wikipedia.org/wiki/Base64

1 comment:

  1. Base64 encoding can be applied to boost front end performance increase, utilizing local storage. More at my iSkeleton Framework - iskeleton.blogspot.com

    ReplyDelete