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 :: canvas rounded corners on image 
Javascript :: flatten an array javascript 
Javascript :: how to align text inside react component 
Javascript :: send mail in node js without password 
Javascript :: react native image 
Javascript :: liquid object 
Javascript :: how to write a json in r 
Javascript :: prototype in javascript 
Javascript :: javascript sleep 1 second” is a pretty common code problem that people search ;-) 
Javascript :: how to add data to array in javascript dynamically 
Javascript :: new date null javascript 
Javascript :: get list of all attributes jqery 
Javascript :: access variable from another function javascript 
Javascript :: how to run electron and react using concurrently 
Javascript :: match city regex 
Javascript :: max value from array in javascript 
Javascript :: Scroll elementleft using js 
Javascript :: javascript foreach url parameter 
Javascript :: how to get last child element in javascript 
Javascript :: classes in es6 
Javascript :: ERROR in ./node_modules/react-icons/all.js 4:0-22 
Javascript :: networkx check if node exists 
Javascript :: how to replace empty string with undefined 
Javascript :: javascript input 
Javascript :: how to stop type text texbox in javascript 
Javascript :: js array.splice first element 
Javascript :: setinterval javascript 
Javascript :: how to get url parameter using jquery or plain javascript 
Javascript :: javascript find in nested array 
Javascript :: Sort an array to have specific items 
ADD CONTENT
Topic
Content
Source link
Name
7+4 =