• Post Reply Bookmark Topic Watch Topic
  • New Topic

Primitive type casting  RSS feed

 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,




How come the output is -17504? Can anyone please explain it to me?

Thanks.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A short only holds 16 bits. If the first bit of the number is 1, then the number is negative.
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply.Could you please explain bitwise(step by step).
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!