Why does this two's complement shortcut work?

一个人想着一个人 提交于 2019-12-05 19:11:57

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!