【问题标题】:representation of hexadecimal numbers in c [duplicate]c中十六进制数字的表示[重复]
【发布时间】:2014-01-12 21:49:48
【问题描述】:

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

00000004
00000008
00000009
0000000d
00000100

【问题讨论】:

  • “我需要将它们表示为十六进制数字。” - 请澄清。
  • 您的意思是要将十六进制表示法的字符串转换为整数吗?
  • @0xbe5077ed 我想将我读取的这些字符串(具有十六进制格式)转换为十六进制数字。
  • @KarolyHorvath 编译器应该将这个十六进制格式的字符串视为十六进制数字。
  • strtol() 是你想要的。

标签: c hex


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    由于您想从文件中读取这些数字,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); 中使用此检查来读取直到最后一个数字。

    【讨论】:

    • 更好地使用unsigned h;
    • 好的,谢谢!还有3个去
    • "\n" in "%x\n" 毫无用处。建议去掉。 "%x" 已经占用了前导空格。 fscanf(f, "%x\n", &h) 将返回 1,在数字后面有或没有 \n
    • "如果您使用的数字超过 4 位,..." 因为 unsigned 至少只有 0 到 65535。最好在此处使用 unsigned long .
    • @user9000 建议 "%lx\n"unsigned long 一起使用。顺便说一句:“无符号默认为无符号长整数”是 not 所以。 unsigned,与unsigned int 相同,除了至少具有unsigned short 的范围且不超过unsigned long 的范围外,不默认为任何其他值。根据 C 规范 §5.2.4.2.1,最小 unsigned 范围与最小 unsigned short 范围相同。
    猜你喜欢
    • 2014-05-24
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2021-03-04
    • 1970-01-01
    • 2018-05-31
    • 2014-12-12
    相关资源
    最近更新 更多