// 第一种方法
NSMutableString* resultAsHexBytes = [NSMutableString string];
NSString *string = @"abc";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
[data enumerateByteRangesUsingBlock:^(const void *bytes,
NSRange byteRange,
BOOL *stop) {
// To print raw byte values as hex
for (NSUInteger i = 0; i < byteRange.length; ++i) {
[resultAsHexBytes appendFormat:@"%02x", ((uint8_t*)bytes)[i]];
}
NSLog(@"resultAsHexBytes:%@", resultAsHexBytes);
}];
// 第二种方法
NSMutableString *result = [NSMutableString string];
const char *bytes = [data bytes];
for (int i = 0; i < [data length]; i++)
{
[result appendFormat:@"%02hhx", (unsigned char)bytes[i]];
}
NSLog(@"result:%@", result);
输出结果分别是:
result:616263
resultAsHexBytes:616263
值得注意的是,第一种方法只适用于iOS7之后的系统。