简体   繁体   中英

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"

When I have

value = atoi(ascii);

It returns value = 3 not 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.

How it can be done ?

The problem is atoi doesn't parse hex. You need a function that parses a hex digit. sscanf(ascii, "%x", &i) comes to mind...

As pointed by others atoi doesnt parse 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

or you can use strol like this:

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

IDEONE SAMPLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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