【问题标题】:Comparing character array contatinig hexa values比较包含十六进制值的字符数组
【发布时间】:2012-05-02 02:13:31
【问题描述】:

我正在通过以下方式接收 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};

请帮忙

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    如果您将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!");
    }
    

    【讨论】:

    • 如果NSArray 中有多个NSData 对象,则此方法有效。只需遍历它们并检查范围以查看是否匹配。
    • 你也可以帮我看看来自服务器的数据,因为服务器是一个设备,有时它会发送奇怪的数据包,那么如何通过 NSLog 和 UIAlert 查看该数据,请帮忙
    • 您可以使用%@NSLog 一个NSData 对象。 NSLog(@"%@", data);.
    • 我想在数据库中添加服务器命令作为字符串,你能帮我如何将它转换成 NSString
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 2011-12-31
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多