A Simple question

Dave Eisen dkeisen at Gang-of-Four.Stanford.EDU
Mon Apr 9 15:52:25 AEST 1990


In article <1881 at zipeecs.umich.edu> yhe at eecs.umich.edu (Youda He) writes:
>Here is the sample program:
>main()
>{
>  char a=255;
>  unsigned char b = 255;
>  printf("a=%X\n",a);
>  printf("b=%X\n",b);
>}
>
>The result is 
>a=FFFF
>b=FF
>on dos, by using zortech and mcs, char is 8 bit long, why a looks like 16bit?

In a sense, it *is* 16 bits. C converts all chars to ints before passing them
to a function. 

a = 255 puts 11111111 into a, b = 255 also puts 11111111 into b. The difference
appears when the two variables are extended to being 2 bytes long.

As an unsigned value, b is extended by tacking 0's to the front to become
000000011111111, still FF as it should be.

But a is signed and extending it by tacking 0's to the front doesn't work if
you are extending negative numbers. In a two's complement system, unsigned 
chars are extended by tacking on whatever appears in the most significant bit 
in the original character so a becomes 1111111111111111, or FFFF.



--
Dave Eisen                      	    Home:(415) 324-9366 / (415) 323-9757
814 University Avenue                       Office: (415) 967-5644
Palo Alto, CA 94301 		            dkeisen at Gang-of-Four.Stanford.EDU 



More information about the Comp.lang.c mailing list