简体   繁体   中英

How to convert number to decimal string?

Hi everyone (newbie here),

I work on an embedded system and I need to convert hex number to an ASCII string.

Please read before answering to understand what I am asking for.

eg hexNumber = 0xFF ASCII = 0x32 0x35 0x35

The ASCII bytes are representation of the decimal value of the hexNumber. Ie 0xFF is 255, 0xFE will be 254, etc...

Essentially, each byte should generate 3 bytes for the decimal representation of the hex number.

The value is not entered using the keyboard, it is a value obtained from a smart card.

You can use the C-style sprintf() for this:

char buf[4];
sprintf(buf, "%03d", 0xFF & (unsigned)byte_to_convert);

You can also use snprintf() , which is generally safer when the output format isn't fixed, but doesn't matter as much for this application.

If your embedded environment can't afford the cost of linking printf family functions from a library (they can be fairly large), then do the conversion with division and modulo, like so:

char buf[4];
buf[3] = 0;   /* NUL trminator */
buf[2] = (unsigned)byte_to_convert       % 10 + '0';
buf[1] = (unsigned)byte_to_convert / 10  % 10 + '0';
buf[0] = (unsigned)byte_to_convert / 100      + '0';

Use snprintf() if you have it, or sprintf() .

Assuming the value is an integer variable, please realize that it's not a "hex value"; it's just a number in a variable. It's not stored in hex inside the computer's memory.

Something like:

int hexNumber = 0xFF;
int i;
char ss[4];

sprintf(ss,"%d",hexNumber);

printf("0x%x: ",hexNumber);

for(i=0;i<3;i++)
    printf("0x%x ",ss[i]);

printf("\n");

This will produce:

0xff: 0x32 0x35 0x35 

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