Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is an optimized version of encoder for the accepted answer, that also supports line-breaking for MIME and other protocols (simlar optimization can be applied to the decoder):</p> <pre><code> char *base64_encode(const unsigned char *data, size_t input_length, size_t *output_length, bool addLineBreaks) *output_length = 4 * ((input_length + 2) / 3); if (addLineBreaks) *output_length += *output_length / 38; // CRLF after each 76 chars char *encoded_data = malloc(*output_length); if (encoded_data == NULL) return NULL; UInt32 octet_a; UInt32 octet_b; UInt32 octet_c; UInt32 triple; int lineCount = 0; int sizeMod = size - (size % 3); // check if there is a partial triplet // adding all octet triplets, before partial last triplet for (; offset &lt; sizeMod; ) { octet_a = data[offset++]; octet_b = data[offset++]; octet_c = data[offset++]; triple = (octet_a &lt;&lt; 0x10) + (octet_b &lt;&lt; 0x08) + octet_c; encoded_data[mBufferPos++] = encoding_table[(triple &gt;&gt; 3 * 6) &amp; 0x3F]; encoded_data[mBufferPos++] = encoding_table[(triple &gt;&gt; 2 * 6) &amp; 0x3F]; encoded_data[mBufferPos++] = encoding_table[(triple &gt;&gt; 1 * 6) &amp; 0x3F]; encoded_data[mBufferPos++] = encoding_table[(triple &gt;&gt; 0 * 6) &amp; 0x3F]; if (addLineBreaks) { if (++lineCount == 19) { encoded_data[mBufferPos++] = 13; encoded_data[mBufferPos++] = 10; lineCount = 0; } } } // last bytes if (sizeMod &lt; size) { octet_a = data[offset++]; // first octect always added octet_b = offset &lt; size ? data[offset++] : (UInt32)0; // conditional 2nd octet octet_c = (UInt32)0; // last character is definitely padded triple = (octet_a &lt;&lt; 0x10) + (octet_b &lt;&lt; 0x08) + octet_c; encoded_data[mBufferPos++] = encoding_table[(triple &gt;&gt; 3 * 6) &amp; 0x3F]; encoded_data[mBufferPos++] = encoding_table[(triple &gt;&gt; 2 * 6) &amp; 0x3F]; encoded_data[mBufferPos++] = encoding_table[(triple &gt;&gt; 1 * 6) &amp; 0x3F]; encoded_data[mBufferPos++] = encoding_table[(triple &gt;&gt; 0 * 6) &amp; 0x3F]; // add padding '=' sizeMod = size % 3; // last character is definitely padded encoded_data[mBufferPos - 1] = (byte)'='; if (sizeMod == 1) encoded_data[mBufferPos - 2] = (byte)'='; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload