使用sp中的sprintf进行十六进制到十进制转换

时间:2015-11-04 08:32:14

标签: c hex printf decimal ascii

我有

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进行十六进制转换,显示它然后将表中的值保存为十进制到另一个变量。

怎么做?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

正如其他人所指出的那样atoi并不解析hex。你可以试试这个:

#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