Objective c decodeHexString obj-c实现,我应该支持奇数长度的HexString吗?如果是,如何支持?

Objective c decodeHexString obj-c实现,我应该支持奇数长度的HexString吗?如果是,如何支持?,objective-c,cocoa,nsstring,hex,Objective C,Cocoa,Nsstring,Hex,我可能在标准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

我可能在标准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;
}
int char2hex(无符号字符c){
开关(c){
案例“0”…“9”:
返回c-‘0’;
案例“a”…“f”:
返回c-‘a’+10;
案例“A”…“F”:
返回c-‘A’+10;
违约:
警告(@“已将非十六进制数字(%s)传递给HexDigitPoint()”,c);
返回0xFF;
}
}
-(NSData*)解码字符串{
断言([自身长度]%2,@“试图解码奇数长度的十六进制字符串。”);
NSData*hexData=[自数据使用编码:NSUTF8StringEncoding];
NSMutableData*resultData=[NSMutableData数据长度:([hexData长度])/2];
常量无符号字符*hexBytes=[hexData字节];
无符号字符*resultBytes=[resultData可变字节];
对于(整数i=0;i<[hexData长度]/2;i++){

resultBytes[i]=(char2hex(hexBytes[i+i])这很可能值得支持。如果
[hexData length]%2
中的for循环前面的
decodeHexString
中的for循环不是零,则可以先去掉第一个数字,然后增加初始循环索引