• Post Reply Bookmark Topic Watch Topic
  • New Topic

Primitive value  RSS feed

 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public short s=(short)(90+900000);

When i print s value ,it is giving -17414.How? I couldn't get the answer when i tried working in paper.Please help me.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
90 + 900000 is 900090, which is a 32-bit int. In binary, this is:

0000 0000 0000 1101 1011 1011 1111 1010

When cast to a 16-bit short, this is:

1011 1011 1111 1010
 
Syamsul Hussin
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Overflow?



gives..



hope this helps.
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thanks for the reply.I was working on the above problem.When i do binary to decimal conversion of 16 bit of short
1011 1011 1111 1010-it gave the answer -48122 instead of giving the answer -17414.My answer is -48122 is not correct.-17414 is the correct answer.but i couldnit still figure out how to get the result.Please share your knowledge.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For signed integral primitives (byte, short, int, and long), a leading 1 indicates a negative value. To determine the quantity, you "flip the bits" (switch all the zeros and ones), then add 1.

1011101111111010 <== Original value

0100010000000101 <== Flipped bits

0100010000000110 <== Add one

Does this help?
[ May 09, 2006: Message edited by: marc weber ]
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marc-Thanks for the reply.It helped me to understand.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See Two's Complement for more detail.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!