在Objective-C中将十六进制字符串转换为二进制

时间:2012-01-21 04:27:28

标签: php objective-c cocoa

什么是PHP函数pack的等价物:

pack('H*', '01234567989abcdef' );
Objective-C中的

2 个答案:

答案 0 :(得分:2)

假设您希望将结果作为NSData,您可以使用与此类似的函数:

NSData *CreateDataWithHexString(NSString *inputString)
{
    NSUInteger inLength = [inputString length];

    unichar *inCharacters = alloca(sizeof(unichar) * inLength);
    [inputString getCharacters:inCharacters range:NSMakeRange(0, inLength)];

    UInt8 *outBytes = malloc(sizeof(UInt8) * ((inLength / 2) + 1));

    NSInteger i, o = 0;
    UInt8 outByte = 0;
    for (i = 0; i < inLength; i++) {
        UInt8 c = inCharacters[i];
        SInt8 value = -1;

        if      (c >= '0' && c <= '9') value =      (c - '0');
        else if (c >= 'A' && c <= 'F') value = 10 + (c - 'A');
        else if (c >= 'a' && c <= 'f') value = 10 + (c - 'a');            

        if (value >= 0) {
            if (i % 2 == 1) {
                outBytes[o++] = (outByte << 4) | value;
                outByte = 0;
            } else if (i == (inLength - 1)) {
                outBytes[o++] = value << 4;
            } else {
                outByte = value;
            }

        } else {
            if (o != 0) break;
        }        
    }

    return [[NSData alloc] initWithBytesNoCopy:outBytes length:o freeWhenDone:YES];
}

答案 1 :(得分:1)

请参阅-scanHex...的{​​{1}}方法。