Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

adding binary numbers in javascript

var addBinary = function (a, b) {
  let sum = BigInt(`0b${a}`) + BigInt(`0b${b}`);
  return sum.toString(2);
};
Comment

binary addition javascript

function binaryAddition(a,b){
  var result = "",
      carry = 0;

  while(a || b || carry){
    let sum = +a.slice(-1) + +b.slice(-1) + carry; // get last digit from each number and sum 

    if( sum > 1 ){  
      result = sum%2 + result;
      carry = 1;
    }
    else{
      result = sum + result;
      carry = 0;
    }
    
    // trim last digit (110 -> 11)
    a = a.slice(0, -1)
    b = b.slice(0, -1)
  }
  
  return result;
}

// Tests
[
  ["0","0"],
  ["1","1"],
  ["1","0"],
  ["0","1"],
  ["10","1"],
  ["11","1"],
  ["10","10"],
  ["111","111"],
  ["1010","11"]
].forEach(numbers => 
   document.write(
     numbers[0] + " + " + 
     numbers[1] + " = " + 
     binaryAddition(numbers[0], numbers[1]) + 
     "      <mark> (" +
     parseInt(numbers[0], 2) + " + " + 
     parseInt(numbers[1], 2) + " = " + 
     parseInt(binaryAddition(numbers[0], numbers[1]),2) +
     ")</mark><br>" 
   )
)
document.body.style="font:16px monospace";
Comment

PREVIOUS NEXT
Code Example
Javascript :: react native shaddow 
Javascript :: localtunnel 
Javascript :: jQuery select elements by name 
Javascript :: electronjs npm start in full screen 
Javascript :: exceljs read file 
Javascript :: $(getJson) returning error 
Javascript :: convert timestamp to date javascript 
Javascript :: set cookie in node 
Javascript :: simple game engine in javascript 
Javascript :: how to right plain text format file in node js 
Javascript :: how to use compare password in node js 
Javascript :: canvas umu 
Javascript :: first letter tuUppercase 
Javascript :: how to reverse a string in javascript 
Javascript :: splidejs pauseOnHover 
Javascript :: convert object to boolean javascript 
Javascript :: regex for month 
Javascript :: jquery replace text in button 
Javascript :: node eventemitter emit error 
Javascript :: Round off a number to the next multiple of 5 using JavaScript 
Javascript :: wordpress ajax url 
Javascript :: How to convert data to utf-8 in node.js 
Javascript :: how to check if browser tab is active javascript 
Javascript :: base64 to png nodejs 
Javascript :: javascript random number in range 
Javascript :: livewire file upload progress 
Javascript :: speedtest-net node.js 
Javascript :: javascript date get future 15 minutes 
Javascript :: javascript pdf preview 
Javascript :: ngchange angular 8 
ADD CONTENT
Topic
Content
Source link
Name
4+6 =