简体   繁体   English

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

[英]Hexadecimal to decimal conversion with sprintf in C

I have 我有

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

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

When I have 当我有

value = atoi(ascii);

It returns value = 3 not 63. 它返回value = 3而不是63。

The thing that I want is hexadecimal conversion with sprintf, display it but then save the value inside the table as decimal to another variable. 我想要的是使用sprintf进行十六进制转换,显示它然后将表中的值作为十进制保存到另一个变量。

How it can be done ? 怎么做?

The problem is atoi doesn't parse hex. 问题是atoi不解析十六进制。 You need a function that parses a hex digit. 您需要一个解析十六进制数字的函数。 sscanf(ascii, "%x", &i) comes to mind... 想到了sscanf(ascii, "%x", &i) ......

As pointed by others atoi doesnt parse hex. 正如其他人指出的那样atoi没有解析hex。 You can try this: 你可以试试这个:

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

IDEONE SAMPLE IDEONE SAMPLE

or you can use strol like this: 或者你可以像这样使用strol

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

IDEONE SAMPLE IDEONE SAMPLE

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

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