我有一個文件,其中包含許多行和列的矩陣。它看起來像下面的東西:將字符串數組轉換爲十六進制數字C
fa ff 00 10 00
ee ee 00 00 30
dd d1 00 aa 00
矩陣中的每個條目是一個八位數值的十六進制數。我想將這個文件讀入一個二維數組。
我有兩個問題:
使用在我的代碼的讀取方法,其*包含具有所述矩陣的每一條目(兩個字符)的陣列。我如何將每個條目傳遞給一個變量而不是兩個字符?
當我傳入單個變量,如何將其從字符轉換爲十六進制? 我的意思是「ff」應該轉換爲0xff。
我的部分代碼如下。如果可以使用更好的方法,我可以避免使用標記化函數。
char** tokens;
char** it;
while (fgets(line, sizeof(line), file) != NULL){ /* read a line */
tokens = tokenize(line); // split line
for(it=tokens; it && *it; ++it){
printf("%s\n", *it);
free(*it);
} // end for
} // end while
char** tokenize(const char* str){
int count = 0;
int capacity = 10;
char** result = malloc(capacity*sizeof(*result));
const char* e=str;
if (e) do {
const char* s=e;
e=strpbrk(s," ");
if (count >= capacity)
result = realloc(result, (capacity*=2)*sizeof(*result));
result[count++] = e? strndup(s, e-s) : strdup(s);
} while (e && *(++e));
if (count >= capacity)
result = realloc(result, (capacity+=1)*sizeof(*result));
result[count++] = 0;
return result;
}
你的意思是採取'FA FF 00 10 00'爲數字,那麼我們將得到'1078020018176'蘋果公司的執行? – prehistoricpenguin
不,fa是單個條目。所以我會得到0xfa而不是「fa」。 – drdot
請看下面我的帖子。 – prehistoricpenguin