c表示十六进制数

时间:2013-12-24 17:14:07

标签: c hex

我从文件中读取以下数字。
这些数字读作strings。我需要将它们表示为hexadecimal个数字。
我该怎么做?

00000004
00000008
00000009
0000000d
00000100

2 个答案:

答案 0 :(得分:3)

由于您想从文件中读取这些数字,fscanf对此有帮助:

/* note, if you're using more than 8 digits, 
    this would have to be unsigned long long and instead of %lx you would need %llx */
unsigned long h;
if (fscanf(f, "%lx", &h) == 1)
    do whatever with h
else
    error, check errno

您可以在循环while (fscanf(f, "%x\n", &h) == 1);中使用此检查来读取最后一个数字。

答案 1 :(得分:3)

如果您已将它们读入字符缓冲区,则可以使用strtol从基数16转换(将第16个传递为第3个参数)。

或者,如果您是从文件中阅读它们,则可以fscanf使用%x转化说明符。