Search code examples
ioscomparisoncomparebytensdata

Compare NSData with byte sequence?


Note: in other questions they compare a value stored in NSData objects, not its bytes.

I want to perform something like this:

NSData *d = ...;
if (d == "fff1") {
  ...
}

The only solution I have found:

NSData *d = ...;
NSString *str = [NSString withFormat:@"%@", d];
if ([str isEqualToString:@"<fff1>"] {
  ...
}

But I don't like that I need to add extra surrounding backets in comparison. Are there better solutions?


Solution

  • For purpose of comparing raw data you use memcmp:

    NSData *dataA;
    void *someBuffer;
    if(memcmp([dataA bytes], someBuffer, dataA.length) == 0) ; //they are the same
    

    Note you should watch that length is not too large for any of the buffers.

    EDIT: added NSData procedure:

    Or better yet you could convert your string to NSData and do the comparison on the NSData:

        NSData *d = ...;
        if([d isEqualToData:[NSData dataWithBytes:"fff1" length:sizeof("fff1")]]) {
    
        }