我正在以下列方式接收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};
请帮助
答案 0 :(得分: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!");
}