我可能在标准libs中遗漏了一些东西,但我不这么认为。我有一个当前的实现:
int char2hex(unsigned char c) {
switch (c) {
case '0' ... '9':
return c - '0';
case 'a' ... 'f':
return c - 'a' + 10;
case 'A' ... 'F':
return c - 'A' + 10;
default:
WARNING(@"passed non-hexdigit (%s) to hexDigitToInt()", c);
return 0xFF;
}
}
- (NSData *)decodeHexString {
ASSERT([self length] % 2, @"Attempted to decode an odd lengthed hex string.");
NSData *hexData = [self dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *resultData = [NSMutableData dataWithLength:([hexData length]) / 2];
const unsigned char *hexBytes = [hexData bytes];
unsigned char *resultBytes = [resultData mutableBytes];
for(NSUInteger i = 0; i < [hexData length] / 2; i++) {
resultBytes[i] = (char2hex(hexBytes[i + i]) << 4) | char2hex(hexBytes[i + i + 1]);
}
return resultData;
}
decodeHexString是nsString上的一个类别添加项。
我想知道的是,它是否值得支持奇数长度的十六进制字符串。如果是,我该怎么办?
附笔。
忽略我的调试宏。我知道switch语句中使用的语法是gcc扩展,可能不会在所有编译器中编译。哦,代码也能像发布的那样工作。