I'm writing code for a PIC18F46K22 using the C18 compiler. I want to write the value of an integer \$n\$ in ASCII over the USART to my PC.
For \$n<10\$, it's easy:
Write1USART(n + 0x30); // 0x30 = '0'
This would work for \$10\le{}n\le100\$:
Write1USART((n/10) + 0x30);
Write1USART((n%10) + 0x30);
But this isn't the fastest possible way, probably.
So is there a built-in function or a function somewhere out there that I could just use instead of rolling my own?
Answer
The C18 compiler supports the number-to-ascii family of standard C functions in stdlib.h: itoa()
, ltoa()
, ultoa()
et cetera.
Depending on which compiler / stdlib.h you have, the relevant function prototype would be:
extern char * itoa(char * buf, int val, int base); // signed int
extern char * utoa(char * buf, unsigned val, int base); // unsigned int
or
extern char * itoa(char * buf, int val); // signed int
extern char * utoa(char * buf, unsigned val); // unsigned int
If you were looking for a relatively robust built-in "standard" C way for converting your numbers to ASCII strings, these xtoa()
functions would be the ones to use.
If on the other hand you are constrained to squeeze a few extra cycles or bytes of memory out of the final code, then several of the other answers to your question are the way to go.
No comments:
Post a Comment