Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A method in a <code>NSData</code> category</p> <pre><code>- (NSString*)encodeBase64 { static char* alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; unsigned int length = self.length; unsigned const char* rawData = self.bytes; //empty data = empty output if (length == 0) { return @""; } unsigned int outputLength = (((length + 2) / 3) * 4); //let's allocate buffer for the output char* rawOutput = malloc(outputLength + 1); //with each step we get 3 bytes from the input and write 4 bytes to the output for (unsigned int i = 0, outputIndex = 0; i &lt; length; i += 3, outputIndex += 4) { BOOL triple = NO; BOOL quad = NO; //get 3 bytes (or only 1 or 2 when we have reached the end of input) unsigned int value = rawData[i]; value &lt;&lt;= 8; if (i + 1 &lt; length) { value |= rawData[i + 1]; triple = YES; } value &lt;&lt;= 8; if (i + 2 &lt; length) { value |= rawData[i + 2]; quad = YES; } //3 * 8 bits written as 4 * 6 bits (indexing the 64 chars of the alphabet) //write = if end of input reached rawOutput[outputIndex + 3] = (quad) ? alphabet[value & 0x3F] : '='; value &gt;&gt;= 6; rawOutput[outputIndex + 2] = (triple) ? alphabet[value & 0x3F] : '='; value &gt;&gt;= 6; rawOutput[outputIndex + 1] = alphabet[value & 0x3F]; value &gt;&gt;= 6; rawOutput[outputIndex] = alphabet[value & 0x3F]; } rawOutput[outputLength] = 0; NSString* output = [NSString stringWithCString:rawOutput encoding:NSASCIIStringEncoding]; free(rawOutput); return output; } </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