Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the size to a Base 64 encoded message

Tags:

c

base64

I have a binary string that I am encoding in Base 64. Now, I need to know before hand the size of the final Base 64 encoded string will be.

Is there any way to calculate that?

Something like:

BinaryStringSize is 64Kb EncodedBinaryStringSize will be 127Kb after encoding.

Oh, the code is in C.

Thanks.

like image 829
Uri Avatar asked Oct 07 '09 17:10

Uri


People also ask

How is Base64 size calculated?

Each Base64 digit represents exactly 6 bits of data. So, three 8-bits bytes of the input string/binary file (3×8 bits = 24 bits) can be represented by four 6-bit Base64 digits (4×6 = 24 bits). This means that the Base64 version of a string or file will be at least 133% the size of its source (a ~33% increase).

How big is a Base64 encoded image?

Very roughly, the final size of Base64-encoded binary data is equal to 1.37 times the original data size + 814 bytes (for headers). You can use ContentLength property of the request to determine what the size is in bytes, although if you are uploading more then one image, it might be trickier.

How many bytes is Base64?

Length of data Base64 uses 4 ascii characters to encode 24-bits (3 bytes) of data.

How long is a Base64 string?

BASE64 characters are 6 bits in length. They are formed by taking a block of three octets to form a 24-bit string, which is converted into four BASE64 characters.


1 Answers

If you do Base64 exactly right, and that includes padding the end with = characters, and you break it up with a CR LF every 72 characters, the answer can be found with:

code_size    = ((input_size * 4) / 3); padding_size = (input_size % 3) ? (3 - (input_size % 3)) : 0; crlfs_size   = 2 + (2 * (code_size + padding_size) / 72); total_size   = code_size + padding_size + crlfs_size; 

In C, you may also terminate with a \0-byte, so there'll be an extra byte there, and you may want to length-check at the end of every code as you write them, so if you're just looking for what you pass to malloc(), you might actually prefer a version that wastes a few bytes, in order to make the coding simpler:

output_size = ((input_size * 4) / 3) + (input_size / 96) + 6; 
like image 159
geocar Avatar answered Oct 16 '22 17:10

geocar