why doesn't printf work right? 
Author Message
 why doesn't printf work right?

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);

Quote:
}



Thu, 17 Dec 1992 10:59:00 GMT  
 why doesn't printf work right?

Quote:
>    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.
--

the soi-disant "Planetary Society"!  | {allegra,ihnp4,decvax,utai}!utzoo!henry



Sun, 17 Jan 1993 20:54:00 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. Why doesn't fflush(stdin) work right?

2. Why doesn't f2c produce printf?

3. why my dropdownlist doesn't return right value

4. Don't know why this doesn't work, but

5. SendMessageToDescendants doesn't work right with MDI

6. printf %E format doesn't work on PockePC

7. Why doesn't this function work?

8. Why doesn't this work!?!??!

9. why doesn't Type.IsSubclassOf work for interfaces

10. Why doesn't this work?

11. Help? Why the program doesn't work

12. Why doesn't this work?

 

 
Powered by phpBB® Forum Software