add
and subtract
If you only have the bitwise operations, you can implement addition.
function add(augend, addend) { const sum = augend ^ addend; const carry = augend & addend; return ( carry === 0 ? sum : add(sum, carry << 1) ); }
In the addition of binary integers, if two bits are different, then the corresponding bit in the sum
is 1
. If two bits are 1
, then the corresponding bit in the carry
is 1
. If the carry
contains any 1
bits, then it must be shifted up and added to the sum
.
Two's complement negation is done by flipping all of the bits and adding 1
.
function negate(integer) { return add(~integer, 1); }
With add
and negate
in hand, subtract
is easy.
function subtract(minuend, subtrahend) { return add(minuend, negate(subtrahend)); }