Skip to content

Instantly share code, notes, and snippets.

@nealfennimore
Last active July 6, 2020 02:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nealfennimore/e0fe3aac7434ca9d70b31e682ce8b356 to your computer and use it in GitHub Desktop.
Save nealfennimore/e0fe3aac7434ca9d70b31e682ce8b356 to your computer and use it in GitHub Desktop.
Binary addition in javascript
/**
* Add two bits together and get resulting bits
*
* @param {Number} a bit a
* @param {Number} b bit b
* @returns {Array<Number, Number>} Carry and sum as a result of addition
*/
function addBits(a, b){
return [ +( a && b ), +( a !== b ) ];
}
/**
* Take two arrays of bits and add together
*
* @param {Array<Number>} bitsA Array of bits
* @param {Array<Number>} bitsB Array of bits
* @returns {Array<Number>} Result adding bits
*/
function add(bitsA, bitsB){
const bits = [];
const length = Math.max( bitsA.length, bitsB.length );
// Iterate from LSB
for (let i = length - 1; i >= 0; i--) {
const bitA = bitsA[i] || 0;
const bitB = bitsB[i] || 0;
const [carry, sum] = addBits(bitA, bitB);
if (i === length - 1) {
bits.unshift(carry, sum);
} else {
// Remove head (msb) and add to resulting sum
const msb = bits.shift();
bits.unshift(carry, sum + msb);
}
}
return bits;
}
console.assert(
addBits(1,1).join('') === '10'
);
console.assert(
addBits(0,1).join('') === '01'
);
console.assert(
addBits(1,0).join('') === '01'
);
console.assert(
addBits(0,0).join('') === '00'
);
console.assert(
add([0, 1, 0, 0, 0, 1, 1], [0, 1, 1, 0, 0, 1, 1]).join('') === '01010110'
);
console.assert(
add([1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]).join('') === '0111111'
);
console.assert(
add([1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0]).join('') === '1011111'
);
console.assert(
add([1], [1]).join('') === '10'
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment