繁体   English   中英

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

[英]Hexadecimal to decimal conversion with sprintf in C

我有

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不解析十六进制。 您需要一个解析十六进制数字的函数。 想到了sscanf(ascii, "%x", &i) ......

正如其他人指出的那样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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM