I've developed a solution for binary addition in Javascript.
My initial goal was to solidify my understanding of binary logic by replicating the mechanisms used in digital binary adder circuits in Javascript (no base conversions or bitwise operators used).
You can find a working version of my original project on CodePen.
It's doing a lot more with the DOM than you probably need, but when I plugged in your numbers (with tweaks mentioned below), I was happy to see that it worked!
Working Solution Code << this project is modified from my original project and contains only the code needed to output the correct answer.
This solution assumes that a
and b
are strings of the same length. To use this solution your input variables should be modified to:
var a = "000010100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101"
var b = "110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011"
(I just filled in the missing digits at the front of var a
with zeros.)
As you can see, I recreated all of the components used in a physical implementation of a binary adder circuit:
Half Adder:
function halfAdder(a, b){
const sum = xor(a,b);
const carry = and(a,b);
return [sum, carry];
}
Full Adder:
function fullAdder(a, b, carry){
halfAdd = halfAdder(a,b);
const sum = xor(carry, halfAdd[0]);
carry = and(carry, halfAdd[0]);
carry = or(carry, halfAdd[1]);
return [sum, carry];
}
Logic Gates:
function xor(a, b){return (a === b ? 0 : 1);}
function and(a, b){return a == 1 && b == 1 ? 1 : 0;}
function or(a, b){return (a || b);}
Main Function:
function addBinary(a, b){
let sum = '';
let carry = '';
for(var i = a.length-1;i>=0; i--){
if(i == a.length-1){
//half add the first pair
const halfAdd1 = halfAdder(a[i],b[i]);
sum = halfAdd1[0]+sum;
carry = halfAdd1[1];
}else{
//full add the rest
const fullAdd = fullAdder(a[i],b[i],carry);
sum = fullAdd[0]+sum;
carry = fullAdd[1];
}
}
return carry ? carry + sum : sum;
}
So then, addBinary(a,b)
produces the correct answer!
var a = "000010100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101"
var b = "110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011"
var answer = "110111101100010011000101110110100000011101000101011001000011011000001100011110011010010011000000000";
console.log(addBinary(a, b) == answer); //true
I hope some of what I've done here can be useful to you too!
Number
calls.parseInt
already returns numbers. – Raddie