On converting a Short to a Byte what goes on?
I'm new to Java, from PHP, so spending some time/effort understanding types. Then I came acr开发者_JAVA百科oss this:
Byte bb = new Byte("127");
System.out.println(bb.byteValue());
Short ss = new Short("32727");
System.out.println(ss.shortValue());
System.out.println(ss.byteValue());
Outputs 127, 32727 and -41 ?
Can someone explain to me how it arrived at -41 when the Short 32727 is represented as a byte?
The binary representation of 32727 is 0111111111010111
. The byteValue() of that is just the smallest 8 bits, so 11010111
11010111
is negative since it begins with a 1.
Taking the Two's complement (complement each bit and then add one) gives 101001
which is 2^5 + 2^3 + 2^0 = 32+8+1 = 41
So we have -41.
Java only knows signed types. When you truncate 32727 to 8 bits (i.e. modulo 256), you get 215, which is -41 when interpreted as a signed 8-bit number (215 + 41 = 256 = 28).
The choice of making the Byte
type signed has caused plenty of criticism, since it adds a lot of subtlety to basic serialization operations, for which people generally prefer the int
type for this very reason.
精彩评论