代码之家  ›  专栏  ›  技术社区  ›  Bryan McLemore

解码hexstring obj-c实现,我应该支持奇数长度的hexstring吗?如果支持,怎么做?

  •  1
  • Bryan McLemore  · 技术社区  · 15 年前

    我可能在标准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扩展,可能不会在所有编译器中编译。哦,代码也能像发布的那样工作。

    1 回复  |  直到 15 年前
        1
  •  2
  •   Matt K    15 年前

    这可能值得支持。您可以从剥离第一个数字开始,并增加初始循环索引,如果 [hexData length] % 2 刚好在for循环之前为非零 decodeHexString .

    推荐文章