2

我得到了一个NSData通孔的字符串表示形式NSLog,我想NSData再次构造原始形式以进行测试,这样做的最佳方法是什么?

例如

<fe010200 00000000 00011012>
4

2 回答 2

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);
于 2013-04-12T20:33:55.427 回答
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 中点,以确保您对分解字符串的假设是准确的。

于 2013-03-05T22:02:20.630 回答