首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

cocoa中 base64 encode一个NSData的步骤

2012-09-18 
cocoa中 base64 encode一个NSData的方法// From: http://www.cocoadev.com/index.pl?BaseSixtyFour+ (NSSt

cocoa中 base64 encode一个NSData的方法

// From: http://www.cocoadev.com/index.pl?BaseSixtyFour

+ (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;
??? for (i=0; i < length; i += 3) {
??????? NSInteger value = 0;
??? ??? NSInteger j;
??????? for (j = i; j < (i + 3); j++) {
??????????? value <<= 8;
??? ??? ???
??????????? if (j < length) {
??????????????? value |= (0xFF & input[j]);
??????????? }
??????? }
??? ???
??????? 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];
}

热点排行