Skip to content

Instantly share code, notes, and snippets.

@davedelong
Created August 28, 2013 23:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davedelong/6372482 to your computer and use it in GitHub Desktop.
Save davedelong/6372482 to your computer and use it in GitHub Desktop.
Making sure I get how base-64 encoding works.
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *str = @"Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
char table[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/',
'='
};
NSMutableString *final = [NSMutableString string];
const char *bytes = [data bytes];
NSUInteger bytesLength = [data length];
NSUInteger bytesProcessed = 0;
while (bytesProcessed < bytesLength) {
char firstByte = bytes[bytesProcessed];
char secondByte = bytesProcessed+1 < bytesLength ? bytes[bytesProcessed+1] : 0;
char thirdByte = bytesProcessed+2 < bytesLength ? bytes[bytesProcessed+2] : 0;
uint32_t nextThreeBytes = (firstByte << 16) | (secondByte << 8) | (thirdByte);
char firstSix = (nextThreeBytes & 0xFC0000) >> 18;
char secondSix = (nextThreeBytes & 0x3F000) >> 12;
char thirdSix = secondByte != 0 ? (nextThreeBytes & 0xFC0) >> 6 : 64;
char fourthSix = thirdByte != 0 ? (nextThreeBytes & 0x3F) : 64;
[final appendFormat:@"%c%c%c%c", table[firstSix], table[secondSix], table[thirdSix], table[fourthSix]];
bytesProcessed += 3;
}
NSLog(@"\n%@", final);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment