4

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;
7

In Java, ints are stored using a 32-bit 2's complement representation and shorts 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.

  • maybe I am missing something in your demonstration, but I would have said that the binary representation of 17 is 10001 rather than 1001 – Seki Dec 1 '14 at 13:17
  • @Seki: Good catch. I have corrected it. – Bart van Ingen Schenau Dec 1 '14 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.