简体   繁体   中英

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?

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")]]) {

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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