Reputation: 103
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.
Upvotes: 0
Views: 1469
Reputation: 386
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
Upvotes: 1
Reputation: 17956
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';
Upvotes: 5
Reputation: 400129
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.
Upvotes: 1