objective-cparsingnsdata

Objective-C: How to parse NSData? How to break into smaller pieces?


I have the following data inside an NSData object:

<00000000 6f2d840e 31504159 2e535953 2e444446 3031a51b 8801015f
 2d02656e 9f110101 bf0c0cc5 0affff3f 00000003 ffff03>

This data contains information which is marked by tags:

Tag 1 is from byte value 0x84 to 0xa5,

Tag 2 is from byte value 0xa5 to 0x88,

Tag 3 is from byte value 0x88 to 0x5f2d,

Tag 4 is from byte value 0x5f2d to 0x9f11.

How would I go about to get the values of these "tags" from the NSData object?

Regards, EZFrag


Solution

  • I managed a nice solution, deciding to actually use the graymatter

    -(int)getIndexOfSubDataInData:(NSData*)haystack forData:(NSData*)needle{
        int dataCounter = 0;
        NSRange dataRange = NSMakeRange(dataCounter, [needle length]);
        NSData* compareData = [haystack subdataWithRange:dataRange];
    
        while (![compareData isEqualToData:needle]) {
    
            dataCounter++;
            dataRange = NSMakeRange(dataCounter, [needle length]);
            compareData = [haystack subdataWithRange:dataRange];
        }
    
        return dataCounter;
    }
    
    -(NSData*)getSubDataInData:(NSData*)targetData fromTag:(NSData*)fromTag toTag:(NSData*)toTag{
    
        int startIndex = [self getIndexOfSubDataInData:targetData forData:fromTag] + [fromTag length];
        int endIndex = [self getIndexOfSubDataInData:targetData forData:toTag];
        int dataLength = endIndex - startIndex;
    
        NSRange dataRange = NSMakeRange(startIndex, dataLength);
    
        return [targetData subdataWithRange:dataRange];
    }
    
    //here is how I use the code
     NSData* langTagStart=[[NSData alloc] initWithBytes:"\x5F\x2D" length:2];
        NSData* langTagEnd=[[NSData alloc] initWithBytes:"\x9F\x11" length:2];
    
        NSData* languageData = [self getSubDataInData:[response bytes] fromTag:langTagStart toTag:langTagEnd];
    

    Thanks for your suggestions.

    Regards, EZFrag