简体   繁体   English

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

[英]Converting a hexadecimal string into binary in Objective-C

What's an equivalent of the PHP function pack : PHP功能pack的等效功能是什么:

pack('H*', '01234567989abcdef' );

in Objective-C? 在Objective-C中?

Assuming that you want the results as an NSData, you can use a function similar to this: 假设您希望将结果作为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];
}

-scanHex...的方法NSScanner

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM