|
|
View previous topic :: View next topic |
Author |
Message |
pl7
Joined: 15 Mar 2007 Posts: 2 Location: UK
|
Using printf to output hexadecimal |
Posted: Thu Apr 30, 2009 7:55 am |
|
|
Hi,
An easy question, I hope. I'm puzzled by the behaviour of printf on a PIC 18F452.
Code: |
int8 a;
a = 1;
printf("%d", a);
|
produces 1, but
Code: |
int8 a;
a = 1;
printf("%x", a);
|
produces 01.
This seems to be incorrect to me. I expected a single hex character for values of a < 16. Is the extra zero a CCS "feature"? Does anyone know how to achieve a single character using the printf format specification?
Thanks,
Phil |
|
|
treitmey
Joined: 23 Jan 2004 Posts: 1094 Location: Appleton,WI USA
|
|
Posted: Thu Apr 30, 2009 8:37 am |
|
|
If your just trying to print a 1 thats easy.
Do it via printing the character.
The character 1 is ascii 49.
So to change 0x01 to 0x31 you add 0x30.
The more common way is to add '0' Code: | #include <18F4620.h>
#fuses hs,nowdt,noprotect,nolvp,put
#use delay(clock=18432000,RESTART_WDT)
#use rs232(baud=19200,xmit=PIN_E0,invert,stream=DEBUG)
#use rs232(baud=1200,errors,xmit=PIN_C6,rcv=PIN_C7,parity=e,enable=PIN_C5,bits=8,stream=CIM)
#case
void main()
{
int8 k=1;
k=k+'0';
//fprintf(DEBUG,"%X\n\r",k);
fprintf(DEBUG,"%C\n\r",k);
while (1)
{
}
}
|
|
|
|
FvM
Joined: 27 Aug 2008 Posts: 2337 Location: Germany
|
|
Posted: Thu Apr 30, 2009 9:13 am |
|
|
Use standard a format string (%x seems to default to %02x):
|
|
|
pl7
Joined: 15 Mar 2007 Posts: 2 Location: UK
|
|
Posted: Thu Apr 30, 2009 9:30 am |
|
|
FvM wrote: | Use standard a format string (%x seems to default to %02x):
|
This was my first thought too, but the width part of the format string specifies a minimum number of digits, not a maximum, so it seems strange to specify a minimum width when really I want to shorten the output. However, I'm sure you are right: CCS is simply substituting %02x for %x, so your solution will work.
Sorry, I would normally have just tried this myself but I have no access to any hardware at the moment.
Thanks for the input,
Phil |
|
|
Ttelmah Guest
|
|
Posted: Thu Apr 30, 2009 9:35 am |
|
|
I suspect the 'reason', is quite logical, when you think that a int8, is inherently two hex digits.
Just another CCS oddity.
Best Wishes |
|
|
FvM
Joined: 27 Aug 2008 Posts: 2337 Location: Germany
|
|
Posted: Thu Apr 30, 2009 1:18 pm |
|
|
Quote: | Sorry, I would normally have just tried this myself but I have no access to any hardware at the moment. | You don't actually need it. I was using MPLAB SIM, cause I didn't want to re-flash a board for this trivial test.
Quote: | Just another CCS oddity. | Yes. I'm satisfied so far, if CCS C understands standard format specifiers, which is the case, fortunately. |
|
|
|
|
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
|