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.
Check out the b64 library. The function b64_encode2() can give a maximum estimate of the required size if you pass
NULL
, so you can allocate memory with certainty, and then call again passing the buffer and have it do the conversion.I think this formula should work:
This formula adds a terminating
CRLF
(MIME, rfc2045) if and only if the last line does not fit exactly in max line length.Here is a simple C implementation (without modulus and trinary operators) for raw base64 encoded size (with standard '=' padding):
To that you will need to add any additional overhead for CRLF if required. The standard base64 encoding (RFC 3548 or RFC 4648) allows CRLF line breaks (at either 64 or 76 characters) but does not require it. The MIME variant (RFC 2045) requires line breaks after every 76 characters.
For example, the total encoded length using 76 character lines building on the above:
See the base64 wikipedia entry for more variants.
Base 64 transforms 3 bytes into 4.
If you're set of bits does not happen to be a multiple of 24 bits, you must pad it out so that it has a multiple of 24 bits (3 bytes).
The actual length of MIME-compliant base64-encoded binary data is usually about 137% of the original data length, though for very short messages the overhead can be a lot higher because of the overhead of the headers. Very roughly, the final size of base64-encoded binary data is equal to 1.37 times the original data size + 814 bytes (for headers).
In other words, you can approximate the size of the decoded data with this formula:
Source: http://en.wikipedia.org/wiki/Base64