This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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
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.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
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.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus