-
StackOverflow 文档
-
Objective-C Language 教程
-
NSData
-
NSData 和十六进制字符串
从十六进制字符串中获取 NSData
+ (NSData *)dataFromHexString:(NSString *)string
{
string = [string lowercaseString];
NSMutableData *data= [NSMutableData new];
unsigned char whole_byte;
char byte_chars[3] = {'\0','\0','\0'};
int i = 0;
int length = (int) string.length;
while (i < length-1) {
char c = [string characterAtIndex:i++];
if (c < '0' || (c > '9' && c < 'a') || c > 'f')
continue;
byte_chars[0] = c;
byte_chars[1] = [string characterAtIndex:i++];
whole_byte = strtol(byte_chars, NULL, 16);
[data appendBytes:&whole_byte length:1];
}
return data;
}
从数据中获取十六进制字符串:
+ (NSString *)hexStringForData:(NSData *)data
{
if (data == nil) {
return nil;
}
NSMutableString *hexString = [NSMutableString string];
const unsigned char *p = [data bytes];
for (int i=0; i < [data length]; i++) {
[hexString appendFormat:@"%02x", *p++];
}
return hexString;
}