Could anyone explain why short(100000) is -31072 as said in p.48 of java-notes.The article says that “the value -31072 is obtained by taking the the 4 byte int 100000 and throwing away two of these bytes to obtain a short”.
The code in the article related to the question is:
int A;
short B;
A = 17;
B = (short)A;
In Java, int
s are stored using a 32-bit 2’s complement representation and short
s with a 16-bit 2’s complement representation.
This means that an int
with the value 17 will contain the bitpattern 00000000 00000000 000000000 00010001
and with the value 100000 it will contain the bitpattern 00000000 00000001 10000110 10100000
.
When converting these numbers to short
, you need to stuff them in 16 bits. This is done by keeping the lower (right-most) 16 bits and throwing the rest away, as that preserves any value that can be represented in a short
.
The pattern for 17 becomes 00000000 00010001
, which still is the number 17.
The pattern for 100000 becomes 10000110 10100000
. Here we have lost one bit that was actually needed for the representation of the number, so the value represented by the remaining bits is different. According to 16-bit 2’complement representation,the bitpattern 10000110 10100000
represents the number -31072.
2