Binary numbers

Arathi Rajashekar
Ranch Hand
Posts: 112
Hi all,
I have doubt. Can anybody explain me how to take 2's comlement of a -ve number.
What I know is we have to invert all 0's to 1 and 1 to 0. and add 1. The result will represent the 2's complement of -ve number
But I tried that way
Example -5
5 => 00000101
by inverting 0 to 1 and 1 to 0's
11111010
-5 => 11111011
This value is correct when I checked it out using toBinaryString() of Integer class
But when I tried with -12
I did the same way as above
12 => 00001100
inverting we get 11110011
-12=> 11110011
Whereas when i found out the value for -12 with toBinaryString(), the answer was 11110100
The same thing is happening for other numbers also. For some number 2' complement procedure is working for other number it is not. So please tell me how to solve this.

Shivaji Marathe
Ranch Hand
Posts: 203
Arathi
Here is part of your post
I did the same way as above
12 => 00001100
inverting we get 11110011
-12=> 11110011

you have inverted 12 but not added 1 to it.
Inverting 12 , we get 11110011 ,
when you add 1 to it
you get 11110100
which is -12.
Hope this helps

Arathi Rajashekar
Ranch Hand
Posts: 112
Originally posted by Shivaji Marathe:
Arathi
Here is part of your post

you have inverted 12 but not added 1 to it.
Inverting 12 , we get 11110011 ,
when you add 1 to it
you get 11110100
which is -12.
Hope this helps

Thanks shivaji. I got it. Will you tell me one more thing when you are adding one which kind of binary addition you are doing

Dave Vick
Ranch Hand
Posts: 3244
Arathi
It looks like your problem is in the adding of 1 to the number. When you add a number in base 10 we all know you have to 'carry' anything over 10 to the next number, the same ting applies to binary numbers too (as well as hex, octal and all the others).