January 6, 2010

Rules for bits in Java

All integer literals are, by default, ints in Java. All floating point literals are, by default, doubles. If a value larger than allowed is put into a given primitive type, the leftmost bits are discarded. So,

char c = (char) 65656; // Binary 00000000000000010000000001111000
byte i = (byte) 130; // Binary 00000000000000000000000010000010

A char is 16 bits, so it is set to 0000000001111000, which equals 1111000, which is 120, which in turn is the character 'z'; a byte is eight bits, so it is set to 10000010. Since the first bit is a sign bit, this actually equals -126. (By two's complement, 10000010 = -(01111101 + 1) = -(01111110) = -126.)

No comments:

Post a Comment