[comp.lang.c] why doesn't printf work right?

brian@ncrcan.UUCP (Brian Onn) (07/30/87)

Reply-To:



	Why does the following code output ffffffff, instead of simply ff,
which I expected from it?  Size of short is 16 bits.   I have tried this on
a Sun, Vax 11/750, and an NCR Tower.

main()
{
	short i = -1;

	printf("%2.2x\n",i);
}

henry@utzoo.UUCP (Henry Spencer) (08/03/87)

> 	Why does the following code output ffffffff, instead of simply ff,
> which I expected from it?  Size of short is 16 bits.   I have tried this on
> a Sun, Vax 11/750, and an NCR Tower.
> 
> main()
> {
> 	short i = -1;
> 
> 	printf("%2.2x\n",i);
> }

Because the value, converted to unsigned as the x format requires, with
32-bit ints, is 0xffffffff, not 0xff.  You have specified a field width
of 2 characters, but the value will not fit in that field.  Some languages
will truncate the value in this case, or fill the field with some sort of
error indication, but C's philosophy is that printing the full, correct value
is more important than obeying the width specification.  Printf is working
correctly, conforming to its documented behavior.

Perhaps you are confused about the meaning of the ".2"?  For x format, that
has no meaning at all in traditional C, and specifies a *minimum* number of
digits in more modern C.  Printf in general will not lie about numeric values
by truncating them; you'll have to do the truncation yourself beforehand.
-- 
Support sustained spaceflight: fight |  Henry Spencer @ U of Toronto Zoology
the soi-disant "Planetary Society"!  | {allegra,ihnp4,decvax,utai}!utzoo!henry