• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

Primitive type casting  RSS feed

 
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.
 
Ranch Hand
Posts: 2410
  • 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: 2410
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!