有些时候我们会用到十六进制字符串的字节码来转换成NSData并进行操作,方法如下:
// NSData转普通字符串
+ (NSString *)DataToString:(NSData *)data {
NSMutableArray *strArr = [[NSMutableArray alloc] init];
for (int i = 0; i < data.length; i++) {
NSString *utf8Str = [NSString stringWithUTF8String:[[data subdataWithRange:NSMakeRange(i, 1)] bytes]];
if (utf8Str) {
[strArr addObject:utf8Str];
}
}
return [strArr componentsJoinedByString:@""];
}
// NSData转十六进制字符串
+ (NSString *)DataToHexString:(NSData *)data {
NSUInteger length = data.length;
NSMutableString *hexStr = [NSMutableString stringWithCapacity:length * 2];
const unsigned char *byte = data.bytes;
for (int i = 0; i < length; i++, byte++) {
[hexStr appendFormat:@"%02X", *byte];
}
return hexStr;
}
// 十六进制字符串转NSData
+ (NSData *)HexStringToData:(NSString *)hexStr {
hexStr = [hexStr stringByReplacingOccurrencesOfString:@" " withString:@""];
hexStr = [hexStr lowercaseString];
NSUInteger len = hexStr.length;
if (!len) return nil;
unichar *buf = malloc(sizeof(unichar) * len);
if (!buf) return nil;
[hexStr getCharacters:buf range:NSMakeRange(0, len)];
NSMutableData *result = [NSMutableData data];
unsigned char bytes;
char str[3] = { '\0', '\0', '\0' };
int i;
for (i = 0; i < len / 2; i++) {
str[0] = buf[i * 2];
str[1] = buf[i * 2 + 1];
bytes = strtol(str, NULL, 16);
[result appendBytes:&bytes length:1];
}
free(buf);
return result;
}