View previous topic :: View next topic |
Author |
Message |
SeeCwriter
Joined: 18 Nov 2013 Posts: 160
|
sprintf formatting |
Posted: Tue Jan 26, 2016 11:06 am |
|
|
Code: |
char buf[10];
long val = 9600;
sprintf( buf, "%06ld\r\n", val );
|
Output is: " 09600"
Should be: "009600"
v5.054 PCWHD. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19538
|
|
Posted: Tue Jan 26, 2016 2:44 pm |
|
|
No.
The '6' is the total output width. For 'd' (decimal), there is a leading space, or sign, which is counted.
For things like hex (which doesn't have a leading space), you would get 6 numeric digits.
%06lu
which doesn't have a sign, will print without a space. |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Tue Jan 26, 2016 3:29 pm |
|
|
You can see this with a test program that prints the buffer as hex bytes.
Note the leading space that Ttelmah refers to:
Quote: | 20 30 39 36 30 30 0d 0a 00 00 |
Test program:
Code: | #include <18F4620.h>
#fuses INTRC_IO, NOWDT
#use delay(clock=4M)
#use rs232(baud=9600, UART1, ERRORS)
//=====================================
void main()
{
char buf[10];
long val = 9600;
int8 i;
sprintf( buf, "%06ld\r\n", val );
for(i=0; i < 10; i++)
printf("%x ", buf[i]);
while(TRUE);
} |
|
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19538
|
|
Posted: Wed Jan 27, 2016 2:10 am |
|
|
The key point here is that because 'd' supports 'sign', there has to be a location to store this. If they allowed %06d, to give 009600 for a +ve value, where would they put the sign if it went -ve?. The output width would have to change. So instead a location is allocated and has either ' ' or '-'.
The mistake is that the value is actually an unsigned value, but is then being printed using the signed output format. How wrong this is can be seen with:
Code: |
char buf[10];
long val = 32768;
sprintf( buf, "%06ld\r\n", val );
|
|
|
|
RF_Developer
Joined: 07 Feb 2011 Posts: 839
|
|
Posted: Wed Jan 27, 2016 4:47 am |
|
|
Ttelmah wrote: |
The mistake is that the value is actually an unsigned value, but is then being printed using the signed output format. |
Yes, its a programmer error to expect the d format not to include a sign or a space for one.
Is that even a mistake in terms of C? I'm not so sure. The format is independant of and not reliant on the type of the variable given to it. The variable is effectively just cast to the type the format expects. If d, or any other format, were what in C++ terms, polymorphic and gave different results depending on the type of what it was given, formatting would be all over the place. |
|
|
|