2016-11-18 118 views
0

我有2個字符數組:比較十六進制字符陣列

unsigned char test_1[2] and unsigned char test_2[2]

它們兩者在它的十六進制值。所以,如果我像循環do:

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 

我的問題是,我該如何比較這兩個字符數組?我有許多字符數組,如test_3, test_4, ...., test_ntest_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); 
+2

看看'memcmp()'。 – chux

+0

@chux它沒有工作。我嘗試了它,並沒有停止在'test_5'。我有意用'test_1'填充'test_5'。 – ThomasWest

+0

「它沒有工作」不是一個明確的解釋,什麼試過,結果與預期的結果。 – chux

回答

0

我會建議你sliding_compare。

無論如何,它們都由單個字符序列組成。

+0

你能詳細說一下嗎?順便說一下,test_1 [0]包含「2e」,test_1 [1]包含「g7」 – ThomasWest

+0

「2e」或「g7」看起來像兩個字符,但如果使用wide_char(wchar_t),「2e」似乎是單個字符。
我所說的是'使用寬字符滑動comapring'

1

幾件事情。

如果當你printf("%02x\n", test_1[i])你打印輸出像「g7」,「t7」或「x1」,那麼你有一些問題......(提示:這些都不是有效的十六進制值)

現在,如果你有很多這些數組要比較(test_2,test_3,test_4 ...),那麼也許你應該使用一個2D數組。當測試[1]與你的測試1相同時,測試[2]將與你的測試2 ...相同...(實際上,你可能想從測試[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); 
    } 
} 

,那麼你幾乎堅持做更「手工」:

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"); 
} 
. 
. 
. 
+0

對不起,這是一個不好的例子,我的代碼顯示爲「2e a1 3e」,我的例子太隨機 – ThomasWest

+1

希望你明白如何使用二維數組,我認爲這是你失蹤的主要原因...... – Matthieu

相關問題