0

What is a 2's complement of 2's complement. I know about 2's complement of a positive integer but what about negative integer. What is a 2's complement of a negative integer eg: what is 2's complement of -128, I want the 2's complement of it. What would be the logic in Java ?

Dici
  • 25,226
  • 7
  • 41
  • 82
Sam
  • 736
  • 5
  • 15
  • 27
  • 1
    The question is unclear. Two's complement (note the e) is a way of representing *signed* integer values, both positive ones and negative ones (and zero). The "two's complement of a two's complement" doesn't really make sense. – T.J. Crowder Oct 01 '15 at 12:39
  • +128, of course. True in all languages, not just Java. – duffymo Oct 01 '15 at 12:39
  • Two numbers are always complements of *each other*. So if `b` is the 2's complement of `a`, then `a` is the 2's complement of `b`. The 2's complement of the 2's complement gets you back where you started from. – Ian McLaird Oct 01 '15 at 14:23

1 Answers1

1

You can understand it like this, the negative number is represented as 2's complement. So if you want to get the 2's compliment of the negative number(-128) you can first get the 2's complement of its positive number(128) and then negate the bits and add one to the result. The result will be the 2's compliment of a negative number.

It is like this:

128 1000 0000 // binary representation of 128 
invert bits 0111 1111 
add one 1000 0000 

Also check wiki which says:

The two's-complement system has the advantage of not requiring that the addition and subtraction circuitry examine the signs of the operands to determine whether to add or subtract. This property makes the system both simpler to implement and capable of easily handling higher precision arithmetic. Also, zero has only a single representation, obviating the subtleties associated with negative zero, which exists in ones'-complement systems.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • Your example might be easier to understand if you used a larger number of bits. In this case, you did the 2's complement and ended up with your input number back, which doesn't clearly illustrate that the leading bits would remain 1s in the complement. – Ian McLaird Oct 01 '15 at 14:30