Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Program to Add Two Binary Strings
Next article icon

JavaScript Program to Add Two Binary Strings

Last Updated : 03 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are the various ways to add two binary strings

Using parseInt() and toString()

The parseInt() method used here first converts the strings into the decimal. Ten of these converted decimal values are added together and by using the toString() method, we convert the sum back to the desired binary representation.

Syntax

parseInt(s1,2) + parseInt(s2,2).toString(2);
JavaScript
let s1 = "101010"; let s2 = "1011"; let sum = (     parseInt(s1, 2) +     parseInt(s2, 2) ).toString(2); console.log(sum); 

Output
110101 

2. Using BigInt Method

The approach uses the BigInt method where the binary strings are convereted into BigInt integers, then addition is performed and once again the conversion of the sum is to binary string. This is used to handle large binary numbers.

Syntax

let bigIntValue = BigInt(value);
JavaScript
let s1 = "101010"; let s2 = "1011"; let sum = (a, b) => {     let decSum =         BigInt(`0b${a}`) +         BigInt(`0b${b}`);     return decSum.toString(2); }; console.log(sum(s1, s2)); 

Output
110101 

Using Manual Operation

The manual operations add the binary digits. We initially ensuring that both of the strings are of same length by adding them with leading 0s, and then iterating through the strings from left to right order and adding binary digits while considering the carry.

JavaScript
let str1 = "101010"; let str2 = "1011"; let sum = (m, n) => {     let len = Math.max(         m.length,         n.length     );     m = m.padStart(len, "0");     n = n.padStart(len, "0");     let carry = 0;     let res = "";      for (let i = len - 1; i >= 0; i--) {         let mBit = +m[i];         let nBit = +n[i];         let sum = mBit + nBit + carry;         carry = Math.floor(sum / 2);         res = (sum % 2) + res;     }     return carry ? "1" + res : res; }; console.log(sum(str1, str2)); 

Output
110101 

Using Recursive Approach

The recursive approach adds two binary strings by breaking down the problem into smaller subproblems. It handles the binary addition bit-by-bit from the end, carrying over the extra bit when necessary, until the base case where one of the strings is empty.

JavaScript
function addBinary(a, b) {     if (a.length < b.length) [a, b] = [b, a];     if (b.length === 0) return a;     if (a[a.length - 1] === '1' && b[b.length - 1] === '1') {         return addBinary(addBinary(a.slice(0, -1), b.slice(0, -1)), '1') + '0';     }     if (a[a.length - 1] === '0' && b[b.length - 1] === '0') {         return addBinary(a.slice(0, -1), b.slice(0, -1)) + '0';     }     return addBinary(a.slice(0, -1), b.slice(0, -1)) + '1'; }  console.log(addBinary("1010", "1011")); 

Output
10101 

Using XOR and AND Bitwise Operators

This approach involves using bitwise operators XOR (^) and AND (&) to add two binary strings. The XOR operation helps in summing the bits without carrying over, while the AND operation helps in finding the carry bits. We then shift the carry bits to the left and repeat the process until there are no more carry bits left.

JavaScript
let str1 = "101010"; let str2 = "1011";  let addBinary = (a, b) => {     let x = BigInt(`0b${a}`);     let y = BigInt(`0b${b}`);          while (y !== 0n) {         let carry = x & y;         x = x ^ y;         y = carry << 1n;     }          return x.toString(2); };  console.log(addBinary(str1, str2)); 

Output
110101 

Using Array Methods for Binary Addition

In this approach, we use array methods to perform binary addition. This involves converting the binary strings into arrays, iterating through them to perform the addition, and handling the carry. This method leverages the power of JavaScript array functions to simplify the process.

JavaScript
function binaryAddition(str1, str2) {     // Ensure str1 is the longer string     if (str2.length > str1.length) [str1, str2] = [str2, str1];      // Convert strings to arrays     let arr1 = str1.split('').reverse();     let arr2 = str2.split('').reverse();      let result = [];     let carry = 0;      // Iterate through the arrays and perform binary addition     for (let i = 0; i < arr1.length; i++) {         let bit1 = parseInt(arr1[i], 10);         let bit2 = i < arr2.length ? parseInt(arr2[i], 10) : 0;          let sum = bit1 + bit2 + carry;         result.push(sum % 2);  // Remainder of sum divided by 2         carry = Math.floor(sum / 2);  // Integer division of sum by 2     }      // If there's a carry left, add it to the result     if (carry) result.push(carry);      // Convert result array back to string and reverse it     return result.reverse().join(''); }  // Example usage: let binaryStr1 = "1101"; let binaryStr2 = "1011"; let sum = binaryAddition(binaryStr1, binaryStr2); console.log(sum);  // Output: "11000" 

Output
11000 

Next Article
JavaScript Program to Add Two Binary Strings

G

gauravggeeksforgeeks
Improve
Article Tags :
  • JavaScript
  • Geeks Premier League
  • javascript-string
  • JavaScript-DSA
  • JavaScript-Program
  • Geeks Premier League 2023

Similar Reads

    JavaScript Program to Add n Binary Strings
    In this article, we are going to learn about Adding n binary strings by using JavaScript. Adding n binary strings in JavaScript refers to the process of performing binary addition on a collection of n binary strings, treating them as binary numbers, and producing the sum in binary representation as
    3 min read
    JavaScript Program to Convert Decimal to Binary
    In this article, we are going to learn the conversion of numeric values from decimal to binary. Binary is a number system with 2 digits (0 and 1) representing all numeric values. Given a number N which is in decimal representation. our task is to convert the decimal representation of the number to i
    5 min read
    C Program to Add 2 Binary Strings
    Given two Binary Strings, we have to return their sum in binary form.Approach: We will start from the last of both strings and add it according to binary addition, if we get any carry we will add it to the next digit.Input: 11 + 11Output: 110C// C Program to Add 2 Binary Strings // and Print their B
    8 min read
    Java Program to Add Characters to a String
    We will be discussing out how to add character to a string at particular position in a string in java. It can be interpreted as follows as depicted in the illustration what we are trying to do which is as follows: Illustration: Input: Input custom string = HelloOutput: --> String to be added 'Gee
    4 min read
    JavaScript Program to Add Two Numbers
    We will explore how to add two numbers in JavaScript. Adding two numbers in JavaScript means combining numeric values together using arithmetic addition, which gives us their total sum. There are several methods that can be used to Add Two Numbers in JavaScript, which are listed below: Table of Cont
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences