我有一个文件,其中包含许多行和列的矩阵。它看起来像下面的东西:将字符串数组转换为十六进制数字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