Skip to content

Instantly share code, notes, and snippets.

@benekastah
Created November 7, 2013 20:31
Show Gist options
  • Save benekastah/7361377 to your computer and use it in GitHub Desktop.
Save benekastah/7361377 to your computer and use it in GitHub Desktop.
A bit adder implemented in javascript.
function assertSize(size, value) {
console.assert(size === value.length, 'size mismatch');
}
function not_1(n) {
assertSize(1, n);
return n === '0' ? '1' : '0';
}
function and_1(a, b) {
assertSize(1, a);
assertSize(1, b);
return a === '1' && b === '1' ? '1' : '0';
}
function or_1(a, b) {
assertSize(1, a);
assertSize(1, b);
return a === '1' || b === '1' ? '1' : '0';
}
function xor_1(a, b) {
assertSize(1, a);
assertSize(1, b);
return or_1(a, b) === '1' ?
a !== b ? '1' : '0' :
'0';
}
function nand_1(a, b) {
return not_1(and_1(a, b));
}
function nor_1(a, b) {
return not_1(or_1(a, b));
}
function xnor_1(a, b) {
return not_1(xor_1(a, b));
}
function getCarry(x) {
return x.charAt(0);
}
function getBody(x) {
return x.substr(1);
}
function firstHalf(x) {
return x.substr(0, x.length / 2);
}
function secondHalf(x) {
return x.substr(x.length / 2);
}
function add_half(a, b) {
assertSize(1, a);
assertSize(1, b);
return and_1(a, b) + xor_1(a, b);
};
function add_1(a, b, c) {
var r1 = add_half(a, b);
var r2 = add_half(c, getBody(r1));
return or_1(getCarry(r1), getCarry(r2)) + getBody(r2);
};
function genericAdder(size, halfFn, a, b, c) {
assertSize(size, a);
assertSize(size, b);
var r1 = halfFn(secondHalf(a), secondHalf(b), c);
var r2 = halfFn(firstHalf(a), firstHalf(b), getCarry(r1));
return r2 + getBody(r1);
}
function add_2(a, b, c) {
return genericAdder(2, add_1, a, b, c);
}
function add_4(a, b, c) {
return genericAdder(4, add_2, a, b, c);
}
function add_8(a, b, c) {
return genericAdder(8, add_4, a, b, c);
}
function add_16(a, b, c) {
return genericAdder(16, add_8, a, b, c);
}
function add_32(a, b, c) {
return genericAdder(32, add_16, a, b, c);
}
function add_64(a, b, c) {
return genericAdder(64, add_32, a, b, c);
}
function add_128(a, b, c) {
return genericAdder(128, add_64, a, b, c);
}
function toBinary(size, n) {
var s = n.toString(2),
fill = '0';
if (s.length > size) {
fill = '1';
s = '';
}
while (s.length < size) {
s = fill + s;
}
return s;
}
function toNumber(b) {
return parseInt(b, 2);
}
add_4('1001', '0101', '0'); // => "01110"
toNumber(add_4(toBinary(4, 4), toBinary(4, 4), '0')); // => 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment