简体   繁体   English

比较NSData与字节序列?

[英]Compare NSData with byte sequence?

Note: in other questions they compare a value stored in NSData objects, not its bytes. 注意:在其他问题中,它们比较存储在NSData对象中的值,而不是其字节。

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 : 为了比较原始数据,可以使用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: 编辑:添加了 NSData 过程:

Or better yet you could convert your string to NSData and do the comparison on the NSData : 或者更好的是,您可以将字符串转换为NSData并在NSData上进行比较:

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

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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