var addBtn = document.getElementById("addBtn");
addBtn.addEventListener('click', () => {
var isAdd = true;
action(isAdd);
});
var subBtn = document.getElementById("subBtn");
subBtn.addEventListener('click', () => {
var isAdd = false;
action(isAdd);
});
// add or subtract base on isAdd flag
function action(isAdd){
// get the inputs as integers from string
var a = document.getElementById("inputA").value;
var b = document.getElementById("inputB").value;
if (!isNaN(a) && !isNaN(b)) {
// convert to binary if both are numbers
a = dec2bin(parseInt(a));
b = dec2bin(parseInt(b));
var res;
if (isAdd) {
res = addTwoBinary(a,b);
} else {
res = subTwoBinary(a,b);
}
// array to string, then remove comma from string
document.getElementById("result").innerHTML = res.toString().replace(/,/g, '');
} else {
document.getElementById("result").innerHTML = 'A or B is not a number';
}
}
// returns an inverse binary, used with subtraction
// arr = Array<int>
function inverseBinary(arr){
// flip the digits from 1 to 0, and vice versa
for(var i=0; i<arr.length; i++){
var value = arr[i];
switch(value){
case 0:
arr[i] = 1;
break;
case 1:
arr[i] = 0;
break;
default:
throw new Error('inverse binary failed, case not supported');
}
}
// add 1 after the inverse
return addTwoBinary(arr, dec2bin(1));
}
// subtract two binary - 8-bit only
function subTwoBinary(a,b){
b = inverseBinary(b);
return addTwoBinary(a,b);
}
// add two binary - 8-bit only
function addTwoBinary(a,b){
var finalArray = b.slice(); // final array
var carry = 0;
// add from right to left
for(var i=a.length-1; i>=0; i--) {
var sum = a[i] + b[i] + carry;
switch(sum){
case 0:
finalArray[i] = 0;
carry = 0;
break;
case 1:
finalArray[i] = 1;
carry = 0;
break;
case 2:
finalArray[i] = 0;
carry = 1;
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.