如何从描述中构造NSData?

时间:2013-03-05 21:04:40

标签: objective-c cocoa-touch nsdata

我通过NSData获得了NSLog的字符串表示形式,我想再次构建原始NSData用于测试目的,这是最好的方法吗?< / p>

e.g。

<fe010200 00000000 00011012>

2 个答案:

答案 0 :(得分:0)

我猜是这样的:

NSArray *wordStrings =
    [string componentsSeparatedByCharactersInSet:
        [[NSCharacterSet alphanumericCharacterSet] invertedSet]];

NSMutableData *collectedData = [NSMutableData dataWithCapacity:wordStrings.count * sizeof(unsigned)];

for(NSString *word in wordStrings)
{
    NSScanner *scanner = [NSScanner scannerWithString:word];
    unsigned newInt;
    [scanner scanHexInt:&newInt];
    [collectedData appendBytes:&newInt length:sizeof(unsigned)];
}

在使用NSString强制间距后,它会为每个单词创建一个扫描程序,而在扫描程序中执行所有操作会更有效,但它只是用于调试,对吧?通过这种方式,您可以获得wordStrings中点,以确保您对分解字符串的假设是准确的。

答案 1 :(得分:0)

以下是一些对数字进行简单扫描并将其值附加到NSMutableData对象的行

    NSString *dataIn = @"<fe010200 00000000 00011012>";

    const char *ptr = [dataIn cStringUsingEncoding:NSUTF8StringEncoding];

    NSMutableData *data = [NSMutableData data];

    while (*ptr) {
        unsigned char c1 = *ptr;
        ptr++;
        if (isalpha(c1))
            c1 = (10 + c1 - 'a')<<4;
        else if (isnumber(c1))
            c1 = (c1 - '0')<<4;
        else
            continue;
        if (!*ptr)
            break; // Shouldn't occure -- bad input
        unsigned char c2 = *ptr;
        ptr++;
        if (isalpha(c2))
            c2 = 10 + c2 - 'a';
        else if (isnumber(c2))
            c2 = c2 - '0';
        c1 = c1 | c2;
        [data appendBytes:&c1 length:1];
    }

    NSLog(@"%@", data);