在平常开发中,经常会遇到过NSData
与NSString
相关转换的问题,一般都是用:
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
但是在实际开发过程中会遇到至少如下三种NSData
与NSString
转换
一、字符编码转换
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
上述是最常用的UTF8编码转换,实际上有很多编码,但在绝大多数情况下我们都是使用UTF8编码格式。
具体有哪些编码可以参考:NSStringEncoding
这个枚举值。
二、Base64编码转换
NSString *string = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
三、Hex编码
- (NSString *)stringFromData:(NSData *)data {
Byte *bytes = (Byte *)[data bytes];
NSString *string = @"";
for (NSInteger i = 0; i<data.length; i++) {
NSString *newHexStr = [NSString stringWithFormat:@"%x", bytes[i] & 0xff]; //16进制数
newHexStr = [newHexStr uppercaseString];
if ([newHexStr length] == 1) {
newHexStr = [NSString stringWithFormat:@"0%@",newHexStr];
}
string = [string stringByAppendingString:newHexStr];
}
return string;
}
- (NSData *)dataFromString:(NSString *)string {
const char *ch = [[string lowercaseString] cStringUsingEncoding:NSUTF8StringEncoding];
NSMutableData *data = [NSMutableData data];
while (*ch) {
if (*ch == ' ') {
continue;
}
char byte = 0;
if ('0' <= *ch && *ch <= '9') {
byte = *ch - '0';
} else if ('a' <= *ch && *ch <= 'f') {
byte = *ch - 'a' + 10;
} else if ('A' <= *ch && *ch <= 'F') {
byte = *ch - 'A' + 10;
}
ch++;
byte = byte << 4;
if (*ch) {
if ('0' <= *ch && *ch <= '9') {
byte += *ch - '0';
} else if ('a' <= *ch && *ch <= 'f') {
byte += *ch - 'a' + 10;
} else if('A' <= *ch && *ch <= 'F') {
byte += *ch - 'A' + 10;
}
ch++;
}
[data appendBytes:&byte length:1];
}
return data;
}
网友评论