JavaScript Program to Add Two Binary Strings
Last Updated :
03 Jan, 2025
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);
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));
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));
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"));
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));
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"
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read