Shiva Mohan

Ranch Hand

Posts: 486

Keith Lynn

Ranch Hand

Posts: 2409

Shiva Mohan

Ranch Hand

Posts: 486

Keith Lynn

Ranch Hand

Posts: 2409

posted 11 years ago

First, look at the bit representation of 900,000.

11011011101110100000

Since a short only contains 16 bits, we are only concerned with the last 16 bits.

1011101110100000

Since the first bit is 1, this is a negative number.

To determine what negative number it is, we flip each of the bits and add 1.

When we flip the bits we get

0100010001011111

When we add 1 we get

0100010001100000

This represents the number 17504.

So when you cast 900000 to a short, you get -17504.

11011011101110100000

Since a short only contains 16 bits, we are only concerned with the last 16 bits.

1011101110100000

Since the first bit is 1, this is a negative number.

To determine what negative number it is, we flip each of the bits and add 1.

When we flip the bits we get

0100010001011111

When we add 1 we get

0100010001100000

This represents the number 17504.

So when you cast 900000 to a short, you get -17504.

It is sorta covered in the JavaRanch Style Guide. |