我有2个字符数组:
unsigned char test_1[2] and unsigned char test_2[2]
它们都有十六进制值。所以,如果我做循环,如:
for (i=0; i<sizeof(test_1); i++)
printf("%02x\n", test_1[i])
and
for (i=0; i<sizeof(test_2); i++)
printf("%02x\n", test_2[i])
它将打印如下内容:
2e
50
and
a1
3e
我的问题是,如何比较这两个char数组?我有许多字符数组,如test_3, test_4, ...., test_n
,可与test_1
进行比较。
我使用strcmp()
但失败了,因为它们不是字符串。
******更新*******
代码逻辑:
while(memcmp(test_1, test_n,2) != 0){
// grab the next test_n char array (test_2, test_3, ....)
// set test_n to have same value as the next test_n
}
printf("Stop the search, I found it!"\n);
答案 0 :(得分:1)
一些事情。
如果您执行printf("%02x\n", test_1[i])
时出现“g7
”,“t7
”或“x1
”等打印件,那么您会遇到一些问题...(提示:那些不是有效的十六进制值)
现在,如果你有很多要比较的数组(test_2,test_3,test_4 ......),那么你应该使用2D数组。当test [1]与test_1相同时,test [2]将与你的test_2相同......等等(实际上,你可能想要从test [0]开始,但至少我希望你能理解我想说的话。)
如果您有类似的东西,并且您知道所有这些数组的长度都是2,那么您将能够执行以下操作:
int i;
for(i=2; i<num_arrays; i++) {
if(!memcmp(test[1], test[i], 2) {
printf("Array test_%d is equal to test_1\n", i);
} else {
printf("Array test_%d is different from test_1\n", i);
}
}
如果你不使用2D阵列,那么你很难“手工”做更多的事情:
if (!memcmp(test_1, test_2, 2) {
printf("test_2 is the same\n");
}
if (!memcmp(test_1, test_3, 2) {
printf("test_3 is the same\n");
}
.
.
.
答案 1 :(得分:0)
我建议你使用sliding_compare。
无论如何,它们都由单个字符序列组成。