Base64: What is the worst possible increase in space usage?

Bryan Field picture Bryan Field · Jan 17, 2011 · Viewed 90.8k times · Source

If a server received a base64 string and wanted to check it's length before converting,, say it wanted to always permit the final byte array to be 16KB. How big could a 16KB byte array possibly become when converted to a Base64 string (assuming one byte per character)?

Answer

R. Martinho Fernandes picture R. Martinho Fernandes · Jan 17, 2011

Base64 encodes each set of three bytes into four bytes. In addition the output is padded to always be a multiple of four.

This means that the size of the base-64 representation of a string of size n is:

ceil(n / 3) * 4

So, for a 16kB array, the base-64 representation will be ceil(16*1024/3)*4 = 21848 bytes long ~= 21.8kB.

A rough approximation would be that the size of the data is increased to 4/3 of the original.