Reputation: 53
What is the fastest way to compare unsigned char* and const char* ?
Say, I have
unsigned char* msg; //length is more than 10000
typedef struct {
atomic<bool> updated;
const char cmp[10]="test ";
int id=10000;
} test;
I want to compare msg ( starting from 30th characters) to test.cmp upto 5 length. I am doing the following code
for (int k = 0; k < 5; k++) {
if (*(msg + 30+ k) != test.cmp[k]) {
break;
}
}
Is the correct way or do you suggest something else?
Thanks a lot.
Upvotes: 2
Views: 6507
Reputation: 1140
use strncmp
, this way you can compare the first 5 characters, and by passing msg+30, the first character is the 30th
if (strncmp(reinterpret_cast<const char*>(msg+30), &(test.cmp), 5)==0){
printf("match");
}
http://www.cplusplus.com/reference/cstring/strncmp/
Using memcmp
is a mistake, because cmp is a NULL terminated string and memcmp won't terminate the comparison on the NULL byte.
Upvotes: 4
Reputation: 320
You can give memcmp try. Although i don't know if it will work properly while comparing pointers which differ in sings.
You can also try to change type of msg to just char *, if it does not collide with the rest of your program and use strcmp or strncmp
Upvotes: 0