NSData to base64Encoding

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


阅读更多
文章标签: encoding buffer null
个人分类: iPhone 开发
上一篇iOS code collection
下一篇AVPlayer后台播放音频
想对作者说点什么? 我来说一句

NSData+AESCrypt库

2011年09月10日 5KB 下载

NSData+AESCrypt

2012年11月16日 53KB 下载

没有更多推荐了,返回首页

关闭
关闭