debugHexString obj-c 实现,我是否应该支持奇数长度的十六进制字符串,如果是,如何支持?
我可能在标准库中遗漏了一些东西,但我不这么认为。我当前有这样的实现:
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 上的一个类别添加。
我想知道的是,是否值得支持奇数长度的十六进制字符串。如果是这样,我该怎么办?
PS 忽略我的调试宏。我知道 switch 语句中使用的语法是 GCC 扩展,可能无法在所有编译器中编译。哦,代码确实按照发布的方式工作。
I may be missing something in the standard libs, but I don't think so. I have this current implementation:
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 is a category addition on NSString.
What I'm wondering is, if it's worth supporting odd lengthed hexstrings. And if so, how should i?
P.S. Ignore my debugging macros. And I'm aware that the syntax in use in the switch statement is a GCC extension and may not compile in all compilers. Oh and the code does work as posted.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能值得支持。如果
decodeHexString
中的 for 循环之前的[hexData length] % 2
非零,您可以先去掉第一个数字并递增初始循环索引。It is likely worth supporting. You can start by peeling off the first digit and incrementing your initial loop index if
[hexData length] % 2
is non-zero just before the for loop indecodeHexString
.