Calculate the size to a Base64 encoded message

前端 未结 9 811
暗喜
暗喜 2020-12-15 04:17

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 calcu

9条回答
  •  感动是毒
    2020-12-15 04:52

    Here is a simple C implementation (without modulus and trinary operators) for raw base64 encoded size (with standard '=' padding):

    int output_size;
    output_size = ((input_size - 1) / 3) * 4 + 4;
    

    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:

    int final_size;
    final_size = output_size + (output_size / 76) * 2;
    

    See the base64 wikipedia entry for more variants.

提交回复
热议问题