Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is the code to base64 encode directly to byte array (tested to be performing +-10% of .Net Implementation, but allocates half the memory):</p> <pre><code> static public void testBase64EncodeToBuffer() { for (int i = 1; i &lt; 200; ++i) { // prep test data byte[] testData = new byte[i]; for (int j = 0; j &lt; i; ++j) testData[j] = (byte)(j ^ i); // test testBase64(testData); } } static void testBase64(byte[] data) { if (!appendBase64(data, 0, data.Length, false).SequenceEqual(System.Text.Encoding.ASCII.GetBytes(Convert.ToBase64String(data)))) throw new Exception("Base 64 encoding failed); } static public byte[] appendBase64(byte[] data , int offset , int size , bool addLineBreaks = false) { byte[] buffer; int bufferPos = 0; int requiredSize = (4 * ((size + 2) / 3)); // size/76*2 for 2 line break characters if (addLineBreaks) requiredSize += requiredSize + (requiredSize / 38); buffer = new byte[requiredSize]; UInt32 octet_a; UInt32 octet_b; UInt32 octet_c; UInt32 triple; int lineCount = 0; int sizeMod = size - (size % 3); // adding all data triplets 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; buffer[bufferPos++] = base64EncodingTable[(triple &gt;&gt; 3 * 6) &amp; 0x3F]; buffer[bufferPos++] = base64EncodingTable[(triple &gt;&gt; 2 * 6) &amp; 0x3F]; buffer[bufferPos++] = base64EncodingTable[(triple &gt;&gt; 1 * 6) &amp; 0x3F]; buffer[bufferPos++] = base64EncodingTable[(triple &gt;&gt; 0 * 6) &amp; 0x3F]; if (addLineBreaks) { if (++lineCount == 19) { buffer[bufferPos++] = 13; buffer[bufferPos++] = 10; lineCount = 0; } } } // last bytes if (sizeMod &lt; size) { octet_a = offset &lt; size ? data[offset++] : (UInt32)0; octet_b = offset &lt; size ? data[offset++] : (UInt32)0; octet_c = (UInt32)0; // last character is definitely padded triple = (octet_a &lt;&lt; 0x10) + (octet_b &lt;&lt; 0x08) + octet_c; buffer[bufferPos++] = base64EncodingTable[(triple &gt;&gt; 3 * 6) &amp; 0x3F]; buffer[bufferPos++] = base64EncodingTable[(triple &gt;&gt; 2 * 6) &amp; 0x3F]; buffer[bufferPos++] = base64EncodingTable[(triple &gt;&gt; 1 * 6) &amp; 0x3F]; buffer[bufferPos++] = base64EncodingTable[(triple &gt;&gt; 0 * 6) &amp; 0x3F]; // add padding '=' sizeMod = size % 3; // last character is definitely padded buffer[bufferPos - 1] = (byte)'='; if (sizeMod == 1) buffer[bufferPos - 2] = (byte)'='; } return buffer; } </code></pre>
 

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