Tuesday, July 14, 2009

Why print 144 in output(Turbo c)?

void main(){


unsigned char c;


c = 100 * 4;


printf("%d",c);


}

Why print 144 in output(Turbo c)?
A 'char' is a byte-sized variable. An unsigned byte can only contain a value from 0 to 255. A signed byte can only contain a value from 127 to -128.


The reason you got 144 is because 144 is the lower byte of the number 400. If you declared the variable 'c' as an integer (a two byte variable in 16 bit compilers), then you would have gotten the number 400.


In hexadecimal, the number 400 is this:


01 90


If you convert only the lower 90 byte to decimal, you get 144. So, you see, when you assigned 'c' to be equal to 400, the compiler couldn't fit the whole number into the byte, so it just put the lower byte of the number 400 into the 'c' variable.
Reply:because unsigned char c


composed of 8 bits


100*4=400


400 in binary is 1 1001 0000


unsigned char only takes 1001 0000


it only take 8 bits


1001 0000 in decimal is 144


No comments:

Post a Comment