Created
December 3, 2013 12:39
-
-
Save sag333ar/7768527 to your computer and use it in GitHub Desktop.
Convert NSData to Base64 Encoded String.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (NSString*)base64forData:(NSData*)theData { | |
const uint8_t* input = (const uint8_t*)[theData bytes]; | |
NSInteger length = [theData length]; | |
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; | |
NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4]; | |
uint8_t* output = (uint8_t*)data.mutableBytes; | |
NSInteger i,i2; | |
for (i=0; i < length; i += 3) { | |
NSInteger value = 0; | |
for (i2=0; i2<3; i2++) { | |
value <<= 8; | |
if (i+i2 < length) { | |
value |= (0xFF & input[i+i2]); | |
} | |
} | |
NSInteger theIndex = (i / 3) * 4; | |
output[theIndex + 0] = table[(value >> 18) & 0x3F]; | |
output[theIndex + 1] = table[(value >> 12) & 0x3F]; | |
output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '='; | |
output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '='; | |
} | |
return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment