Created
April 28, 2018 10:02
-
-
Save lqt0223/3bcee9a93e00a2943ed5f85df52bf391 to your computer and use it in GitHub Desktop.
35 binary adder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// a half-adder takes 2 binary bits as input, and return as result the sum and carry flag | |
function halfAdder(a, b) { | |
// the sum is 0 when two bits are the same (1 + 1 or 0 + 0) | |
var s = a ^ b | |
// the carry flag is set when 1 + 1 | |
// the bitwise expression !(a ^ b) is for testing equality between a and b | |
var c = !(a ^ 1) && (!a ^ b) | |
return [c, s] | |
} | |
// a full-adder takes 2 binary bits and a carry flag as input, | |
// and return as result the sum and the carry flag after summation | |
function fullAdder(a, b, cin) { | |
var [c2, tsum] = halfAdder(b, cin) | |
var [c1, sum] = halfAdder(a, tsum) | |
var cout = c1 | c2 | |
return [cout, sum] | |
} | |
// a full-adder can be use to add two numbers in 1 bit | |
// a sequence of full-adders in cascade can be use to add two numbers in N bits | |
function binaryAdder(addend, augend) { | |
addend = addend.split('').map((digit) => { | |
return parseInt(digit) | |
}) | |
augend = augend.split('').map((digit) => { | |
return parseInt(digit) | |
}) | |
return baHelper(addend, augend, 0, []) | |
} | |
function baHelper(addend, augend, cin, result) { | |
if (addend.length === 0 && augend.length === 0) { | |
result.unshift(cin) | |
return result.join('') | |
} else { | |
var a = addend.pop() | |
var b = augend.pop() | |
var [cout, sum] = fullAdder(a, b, cin) | |
result.unshift(sum) | |
return baHelper(addend, augend, cout, result) | |
} | |
} | |
// test: | |
// 0b10010010 + 0b10101010 = 0b10111111111 (binary) | |
// 146 + 170 = 316 (decimal) | |
var result = binaryAdder('10010010', '10101010') | |
console.log(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment