关闭

NSData to base64Encoding

标签: encodingbuffernull
3412人阅读 评论(2) 收藏 举报
分类:

static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

+ (NSString *)base64EncodingWithData:(NSData *)aData
{
	if ([aData length] == 0)
		return @"";
    
    char *characters = malloc((([aData length] + 2) / 3) * 4);
	if (characters == NULL)
		return nil;
	NSUInteger length = 0;
	
	NSUInteger i = 0;
	while (i < [aData length])
	{
		char buffer[3] = {0,0,0};
		short bufferLength = 0;
		while (bufferLength < 3 && i < [aData length])
			buffer[bufferLength++] = ((char *)[aData bytes])[i++];
		
		//  Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.
		characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];
		characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
		if (bufferLength > 1)
			characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
		else characters[length++] = '=';
		if (bufferLength > 2)
			characters[length++] = encodingTable[buffer[2] & 0x3F];
		else characters[length++] = '=';	
	}
	
	return [[[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES] autorelease];
}
 
//ps:这里有一个不错的base64的库:https://github.com/tangqiaoboy/xcode_tool/tree/master/Encoding


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:277493次
    • 积分:3758
    • 等级:
    • 排名:第8562名
    • 原创:61篇
    • 转载:186篇
    • 译文:0篇
    • 评论:19条
    最新评论