//NSString转NSData
- (NSData*)dataWithBase64EncodedString:(NSString*)string
{
if(string ==nil)
[NSException raise:NSInvalidArgumentException format:nil];
if([stringlength] ==0)
return[NSDatadata];
staticchar*decodingTable =NULL;
if(decodingTable ==NULL)
{
decodingTable =malloc(256);
if(decodingTable ==NULL)
returnnil;
memset(decodingTable,CHAR_MAX,256);
NSUIntegeri;
for(i =0; i <64; i++)
decodingTable[(short)encodingTable[i]] = i;
}
const char *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];
if(characters ==NULL) // Not an ASCII string!
returnnil;
char*bytes =malloc((([stringlength] +3) /4) *3);
if(bytes ==NULL)
returnnil;
NSUIntegerlength =0;
NSUInteger i = 0;
while (YES)
{
charbuffer[4];
shortbufferLength;
for(bufferLength =0; bufferLength <4; i++)
{
if(characters[i] =='\0')
break;
if(isspace(characters[i]) || characters[i] =='=')
continue;
buffer[bufferLength] = decodingTable[(short)characters[i]];
if(buffer[bufferLength++] ==CHAR_MAX) // Illegal character!
{
free(bytes);
returnnil;
}
}
if(bufferLength ==0)
break;
if (bufferLength == 1) // At least two characters are needed to produce one byte!
{
free(bytes);
returnnil;
}
// Decode the characters in the buffer to bytes.
bytes[length++] = (buffer[0] <<2) | (buffer[1] >>4);
if(bufferLength >2)
bytes[length++] = (buffer[1] <<4) | (buffer[2] >>2);
if(bufferLength >3)
bytes[length++] = (buffer[2] <<6) | buffer[3];
}
bytes =realloc(bytes, length);
return [NSData dataWithBytesNoCopy:bytes length:length];
}
//NSData转NSString
- (NSString*)base64EncodedStringFrom:(NSData*)data
{
if([datalength] ==0)
return@"";
char*characters =malloc((([datalength] +2) /3) *4);
if(characters ==NULL)
returnnil;
NSUIntegerlength =0;
NSUInteger i = 0;
while(i < [datalength])
{
charbuffer[3] = {0,0,0};
shortbufferLength =0;
while(bufferLength <3&& i < [datalength])
buffer[bufferLength++] = ((char*)[databytes])[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)];
elsecharacters[length++] ='=';
if(bufferLength >2)
characters[length++] =encodingTable[buffer[2] &0x3F];
elsecharacters[length++] ='=';
}
return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
}