Douglas Crockford

Blog

Books

Videos

2024 Appearances

JavaScript

Misty

JSLint

JSON

Github

Electric Communities

Mastodon/Layer8

Flickr Photo Album

ResearchGate

LinkedIn

Pronouns: pe/per

About

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));
}