0

我正在以下列方式接收 NSData

 - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
    { 
    char *ptr = (void *)[data bytes]; // set a pointer to the beginning of your data   bytes

我正在接收数据,然后我需要将此数据与以下数组进行比较

        char ch[3]={0x04,0x01,0X00};

因为数据来自服务器,但数据是动态的,我需要将许多这样的数组与我找到以下方法的服务器数据进行比较,但它是静态方法,但无法以以下方式比较所有数组

     if(*ptr == 0x04) {
       }
      ptr++;
      if(*ptr == 0x01) {
       }
  ptr++;
  if(*ptr==0X00){
       }
but i can not compare all array so please help how 

我可以比较

              char *ptr = (void *)[data bytes];

               char ch[3]={0x04,0x01,0X00};

请帮忙

4

1 回答 1

2

如果您使用一个NSData对象来比较您正在比较的数据 ( ch[3]),那么您可以使用它-[NSData rangeOfData:options:range:]来查找模式。

这是一个例子

//This is just mock up data to represent what would be passed into your method
unsigned char ch1[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x04, 0x01, 0x00, 0x0F }; 
NSData *data1 = [[NSData alloc] initWithBytes:ch1 
                                       length:sizeof(ch1)];
//This is the data used for the comparison
NSData *data2 = [[NSData alloc] initWithBytes:(unsigned char[]){0x04, 0x01, 0x00} 
                                       length:3];

NSRange range = [data1 rangeOfData:data2 
                           options:0 
                             range:NSMakeRange(0, [data1 length])];

if(range.location != NSNotFound)
{
     NSLog(@"Found pattern!");
}
于 2012-05-01T18:13:31.860 回答