Created
December 21, 2012 07:16
-
-
Save anonymous/4351190 to your computer and use it in GitHub Desktop.
base64 encoding of NSString. Copy of AFBase64EncodedStringFromString private static in AFNetworking
This file contains 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
/* | |
* in file.h | |
*/ | |
@interface NSString (base64) | |
+(NSString *) encodeBase64FromString:(NSString *)string; | |
@end; | |
/* | |
* in file.m | |
*/ | |
@implementation NSString (base64) | |
+(NSString *) encodeBase64FromString:(NSString *)string { | |
NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]]; | |
NSUInteger length = [data length]; | |
NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4]; | |
uint8_t *input = (uint8_t *)[data bytes]; | |
uint8_t *output = (uint8_t *)[mutableData mutableBytes]; | |
for (NSUInteger i = 0; i < length; i += 3) { | |
NSUInteger value = 0; | |
for (NSUInteger j = i; j < (i + 3); j++) { | |
value <<= 8; | |
if (j < length) { | |
value |= (0xFF & input[j]); | |
} | |
} | |
static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | |
NSUInteger idx = (i / 3) * 4; | |
output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F]; | |
output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F]; | |
output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '='; | |
output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '='; | |
} | |
return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment