This is how hardware complements. The results of adding per bit are exceptional or (operator ^
in C ++) bits; this is what you get with sum
. But this does not take into account the transfer from the lower bit. Execution is also a bit (operator &
), which gives the initial value of carry
. But executing bit n is a carryover to bit n + 1, so we shift left by moving bit n to bit n + 1 and add it.
We use recursion to add it, because if the results (per bit) before adding the transfer are 1, and the transfer is 1, it will also be performed.
This is a little more subtle why the recursion ends (and, of course, the hardware version is not recursive, but adds additional logic). This is most easily evaluated considering the initial values:
ab carry_in sum carry_out 0 0 0 0 0 1 0 0 1 0 0 1 0 1 0 1 1 0 0 1 0 0 1 0 0 1 0 1 1 1 0 1 1 1 1 1 1 1 0 1
(The column "sum" is the result of a ^ b
without hyphenation.)
On the first recursive call, bit 0 from b will be 0 (because it represents the transfer of bits of the least significant bit, and there is no one or mdash or because of <<
, which moves the value of carry_out bit n to carry_in bit n + 1). And, of course, carry_in of bit 0 will be 0. So, for bit 0 in the first recursive call, the first two lines can occur. This means that no carry_out, and for the next recursion, only the first two lines refer to bits 0 and 1. In other words, each recursion effectively eliminates one set bit from the common hyphenation, as a result of which the propagated hyphen should ultimately be 0. And since it propagates as parameter b, parameter b must become 0.
source share