【问题标题】:Hexadecimal to decimal conversion with sprintf in C在 C 中使用 sprintf 将十六进制转换为十进制
【发布时间】:2016-02-04 15:57:09
【问题描述】:

我有

sprintf(ascii,"%X",number) // number = 63 is a decimal integer`

char ascii[] = {51, 70, 0, 0, 0, .... } 显示为“3F”

当我有

value = atoi(ascii);

它返回 value = 3 而不是 63。

我想要的是用 sprintf 进行十六进制转换,显示它,然后将表中的值作为十进制保存到另一个变量中。

怎么做?

【问题讨论】:

  • atoi 只知道十进制数 - 使用带有基数 16 的 strtol 或带有 %xsscanf
  • 只做value = number;怎么样?
  • 因为,我通过增加或减少值来改变ascii数组的内容,转换为十进制后保存。

标签: c hex printf decimal ascii


【解决方案1】:

问题是 atoi 不解析十六进制。您需要一个解析十六进制数字的函数。想到sscanf(ascii, "%x", &i)...

【讨论】:

    【解决方案2】:

    正如其他人指出的那样 atoi 不解析十六进制。你可以试试这个:

    #include <stdio.h>
    int main()
    {
        char s[] = "3F";
        int x;
        sscanf(s, "%x", &x);
        printf("%u\n", x);
    }
    

    IDEONE SAMPLE

    或者你可以像这样使用strol

    printf("%u\n", strtol("3F", NULL, 16));
    

    IDEONE SAMPLE

    【讨论】:

      猜你喜欢
      • 2017-07-31
      • 2013-07-20
      • 2012-06-17
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      相关资源
      最近更新 更多