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.

e.g. hexNumber = 0xFF ASCII = 0x32 0x35 0x35

The ASCII bytes are representation of the decimal value of the hexNumber. I.e 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.

6

3 Answers

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';
1

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 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest