0

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?

user3798020
  • 75
  • 1
  • 10

1 Answers1

2

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

    }
Matic Oblak
  • 16,318
  • 3
  • 24
  • 43
  • 1
    Well, the problem is most likely in how you represent the data "fff1". Try logging [NSData dataWithBytes:"fff1" length:sizeof("fff1")] and see what happens. These character values have nothing to do with what you are comparing as I can see. The mere luck why your method works is because how "description" method is defined for NSData. If apple changed this method your code would stop working. – Matic Oblak Jul 24 '14 at 13:06
  • Look at this post: http://stackoverflow.com/questions/7317860/converting-hex-nsstring-to-nsdata – Matic Oblak Jul 24 '14 at 13:09
  • Yes it writes `<66666631 00>` but I need to compare with `. It seems your link with answers is correct but it looks even worse than my solution. – user3798020 Jul 24 '14 at 14:25
  • 2
    As I said, the problem is in how you write the comparator (fff1). One thing is a string and another is a hex representation of data. And agin even if your approach works now it might break later if the NSData description method would change.. How about doing something like this: uint8_t rawData[] = {0xff, 0xf1}; NSData *data = [NSData dataWithBytes:rawData length:sizeof(rawData)]; – Matic Oblak Jul 25 '14 at 06:52