5

A shortcut method of forming the two's complement of a binary number is to copy bits from the right until a one-bit has been copied, then complement (invert) the remaining bits.

That's explained on SO here and also on Wikipedia.

What is not explained is why this shortcut works, that is, why does it produce the same result as inverting all the bits and adding one. So, my question is, why does this work?

Community
  • 1
  • 1
Bob Brown
  • 1,463
  • 1
  • 12
  • 25

3 Answers3

6

It works because adding one to a binary number is accomplished by flipping all 1s to 0s from the right until a 0 is reached, flip that to 1 and stop (essentially carrying the overflow of adding 1 to 1).

So one method flips only the bits to the left of the first one, while the other flips all bits, then flips the first 1 (now 0) and the bits to the right of it back.

e.g.:

 01000100
 10111100  // copy bits until a 1 is reached, then flip the rest

vs

 01000100
 10111011  // invert all bits:
+       1  // add one
 10111100
D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

Write the number as x10k (some string of bits followed by a 1 and then k zeroes).

Suppose you complement it and then add one, you'd get first y01k (where y is the complement of x), then the increment carries through the trailing ones and flips the zero back on, to y10k.

Which is the same thing as just complementing x and leaving the tail alone.

harold
  • 61,398
  • 6
  • 86
  • 164
0

So I've found a shortcut; Note:This trick works if you are allowed to use a calculator with binary to decimal conversion available. If there was an MCQ question like; Q)The 8bit 2's complement representation of 5 is .... ,Use the formula = 2^(number of bits) - the number In this case its 8 bits and the number 5 So; (2^8) - 5 2^8=256 256-5= 251 Convert 251 into binary using calculator Then = 11111011 in binary. Works with any number with respect to number of bits.

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 07 '21 at 01:42
  • 1
    This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30522510) – MD. RAKIB HASAN Dec 07 '21 at 13:18