Hello All I am not clear on how to convert a negative number to binary. I used the toBinary method in wrapper class to make some sense but its not clear. Binary for 1 = 0001 whats binary for -1 ? Binary for 2 = 0010 whats binary for -2 ?
Should I just reverse it...so -1 will be 1110 and -2 will be 1101. I am not clear. Please advice Thank you
if you would just invert it, you would have two representations for zero (0000 and 1111)... so they came up with the solution not to represent "-0", and shift all negative values up by one, so after inversion, simply do a binary "add 1", so that the (otherwise wasted) 1111 represents -1, and 1110 is -2 instead of -1 etc.
this also explains why the range of values is unsymmetric (eg. a byte is from -2^8 to 2^8-1)
Notice how the 4th bit is never used, because it represents the sign, in this case 0 means positive. Notice also that because we cannot use the last bit, this 4-bit integer cannot reach the number 8. So this number limits are, in the positive side, 2^3-1.
Let's see the negative side:
Now, remeber that to convert a binary number to negative, you simple invert the bits and add 1, that's to say ~x+1 is the negative value of x. In other words: x == | ~x+1 | is true.
For instance, let's convert 5 (0101) to a negative number. I will not take into account the sign. Let's say x=5
~101 //invert bits (~x) ----- =010 //partial result +001 //add 1 (~x+1) ----- =011 //partial result
The negative number is 1011 with the first bit turned on, because this is a negative number.
Notice how in this case, the negative numbers take adventage of their additional bit, and that is why negative numbers are always one number greater thant the positive ones. The limits of the negative numbers are, in this case: 2^3. In the positive side we could not express the number 8, because we were a bit short.
Play a bit with the Integer.toBinaryString() and you will see. Of course, in that case you would be playing with 32-bin-signed integers.
A shortcut method for finding the negative no of a binary is
"Starting from the right i.e LSB (Least Significant Bit) you find the first one bit. From LSB till the first 1 bit, including the 1 bit keep all the bits as it is and after the 1 bit interchange all other bit 1s to 0s and 0s to 1s"
from right keep 10 as it is remaining part 0010 - interchanging 0s to 1s and 1s to 0s we get 1101 combining the above 2 steps we get