Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Y 2's compliment notion used to store the value of a variable?

 
Deepak Jain
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
As you know in Java, in the binary form for the value of a variable the most significant bit represents the sign and the rest bits represents the value of the variable. The value is stored as 2's compliment of the actual value.
So to get back the actual value we would need to take the 1's compliment first and then add 1 to it ? Why follow this when we could have stored the value directly?
Thanks
Deepu
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
umm... this has nothing to do with SCJP so i think you could post this in another section to get better replies.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Java in General (Intermediate)
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
2s complements work perfectly in binary adders, which are easily composed of and & or gates on the lowest level of microchips. So it's a hardware influenced choice. HERE is the first binary adder that came up on Google. It's good fun to figure these things out.

Another choice is to use the high-order bit for sign and make 2 and -2 identical except for the sign bit. That's easier for humans, but it doesn't work out as well in binary arithmetic.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by deepu jain:
Why follow this when we could have stored the value directly?


The value *is* stored "directly", in 2's complement. 1's complement isn't "more direct" for the computer.

You need to understand that there isn't *the* natural representation for a number. In our culture we use the decimal system, but the romans used roman numbers. In computer source code, we often use octal or hexadecimal, when it's convenient. And then there are several ways to encode numbers in bits - 1's complement, 2's complement, BCD etc.

None of those are more direct than the others - all are equally artificial representations of an abstract concept.

Having said that, the advantage of 2's complement is that for operations such as addition, you don't need to distinguish between negative and positive values - they just work the same way.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic