diff --git a/JavaScript/assets/js/manipulation.js b/JavaScript/assets/js/manipulation.js index 96257ec..331cc18 100644 --- a/JavaScript/assets/js/manipulation.js +++ b/JavaScript/assets/js/manipulation.js @@ -83,10 +83,10 @@ document.getElementById("startBinCalc").addEventListener('click', function(){ let bin1 = calcDezToBin(dezNumberToBin1); let bin2 = calcDezToBin(dezNumberToBin2); - additionTwoBinNumbers(bin1, bin2); + let result = additionTwoBinNumbers(bin1, bin2); + //let numbersForText = fillwithZero(bin1, bin2); - - document.getElementById('binCalcResult').innerText = bin1 + " - " + bin2; + document.getElementById('binCalcResult').innerText = bin1 + " + " + bin2 + " = " + result; } }); @@ -137,25 +137,72 @@ function flipBinString(remainderString) function additionTwoBinNumbers(bin1, bin2) { - let bin1Array = bin1.split(""); - let bin2Array = bin2.split(""); - let tempResult = ""; - - if(bin1Array.length < bin2Array.length) - for(i = 0; i < bin2Array.length; i++) - { - - - - - } - else - for(i = 0; i < bin1Array.length; i++) - { + + let binArrays = fillwithZero(bin1.split(""), bin2.split("")); + let bin1Array = binArrays.first; + let bin2Array = binArrays.second; + let binOverflow = Array.from({length: bin2Array.length}, (v, k) => '0'); + + let tempResult = "" + for(i = bin1Array.length-1; i >= 0; i--){ + if(bin1Array[i] === '0' && bin2Array[i] === '0' && binOverflow[i] === '0') + { + tempResult += '0'; + }else if (((bin1Array[i] === '0' && bin2Array[i] === '1') || (bin1Array[i] === '1' && bin2Array[i] === '0')) && binOverflow[i] === '0') + { + tempResult += '1'; + } + else if (((bin1Array[i] === '0' && bin2Array[i] === '1') || (bin1Array[i] === '1' && bin2Array[i] === '0')) && binOverflow[i] === '1') + { + tempResult += '0'; + binOverflow[i-1] = '1'; + } + else if((bin1Array[i] === '1' && bin2Array[i] === '1') && binOverflow[i] === '0') + { + tempResult += '0'; + binOverflow[i-1] = '1'; + }else if((bin1Array[i] === '1' && bin2Array[i] === '1') && binOverflow[i] === '1') + { + tempResult += '1'; + binOverflow[i-1] = '1'; + } } + if(binOverflow[-1] === '1') + { + tempResult += '1'; + } + tempResult = flipBinString(tempResult); + return tempResult; +} + +function fillwithZero(binArray1, binArray2) +{ + let difference = Math.abs(binArray1.length - binArray2.length); + + if(difference != 0) + { + if(binArray1.length < binArray2.length) + { + for(i = 0; i < difference; i++) + { + binArray1.unshift('0'); + } + } + else + { + for(i = 0; i < difference; i++) + { + binArray2.unshift('0'); + } + } + } + return { + first: binArray1, + second: binArray2 + } } \ No newline at end of file