|
|
View previous topic :: View next topic |
Author |
Message |
kgng97ccs
Joined: 02 Apr 2022 Posts: 97
|
Using itoa() to convert an integer to ASCII characters |
Posted: Mon Jun 06, 2022 11:02 pm |
|
|
I am using CCS C compiler v5.078 within MPLAB IDE v8.92.
I tried to convert a 16-bit integer to four ASCII characters with the following code: Code: | char ASCII_4ch[5];
unsigned int16 num_ui16;
…
itoa(num_ui16, 16, ASCII_4ch);
…
|
Results:
If num_ui16 = 2, ASCII_4ch[] = {"2", NULL, NULL, NULL, NULL}
If num_ui16 = 255, ASCII_4ch[] = {"F", "F", NULL, NULL, NULL}
If num_ui16 = 8107 (0x1FAB), ASCII_4ch[] = {"1", "F", "A", "B", NULL}
Is there any way to “right-justify” the ASCII characters such that they are always presented in four ASCII characters including leading zeros (if any), as follows?
If num_ui16 = 2, ASCII_4ch[] = {"0", "0", "0", "2", NULL}
If num_ui16 = 255, ASCII_4ch[] = {"0", "0", "F", "F", NULL}
If num_ui16 = 8107 (0x1FAB), ASCII_4ch[] = {"1", "F", "A", "B", NULL} — no change
I will appreciate any comments or suggestions. Thank you. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19506
|
|
Posted: Tue Jun 07, 2022 12:04 am |
|
|
Basic answer. No...
itoa is a standard C function, and does not do this.
In standard C, there would be a simple answer by using sprintf, to transfer
to a second string. This normally supports '-' as a format specifier to
right justify. Unfortunately this is a specifier that CCS lacks....
However, provided you don't mind leading zeros, there is a simple answer:
Code: |
char ASCII_4ch[5];
unsigned int16 num_ui16;
sprintf(ASCII_4ch, "%04X", num_ui16);
|
sprintf's hexadecimal output, supports filling with leading zeros (04, instead
of 4 for the width specifier), so for your 255, you will get:
{"0", "0", "F", "F", NULL}
etc..
Hopefully this is OK.
If not, it can be done by moving the string using strlen to find how long
the number is, and adding leading spaces. Fiddly though... |
|
|
kgng97ccs
Joined: 02 Apr 2022 Posts: 97
|
|
Posted: Tue Jun 07, 2022 3:26 am |
|
|
Thank you so much, Ttelmah.
Yes, the sprintf gives the exact results we are looking for (we need the leading zeros in character form).
We also have a need to put two 8-bit integers into a character array, and I tried, as an example, the following sprintf code: Code: | char ASCII_4ch[5];
sprintf(ASCII_4ch, "%02X", 0xC1);
sprintf(ASCII_4ch+2, "%02X", 0x34); |
The sprintf really helps. Result: ASCII_4ch[] = "C134"
Thanks again. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19506
|
|
Posted: Tue Jun 07, 2022 4:46 am |
|
|
Brilliant.
Glad it was what you wanted. |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|