C Program to Add 2 Binary Strings
Last Updated :
12 Jul, 2024
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 + 11
Output:
110
C
// C Program to Add 2 Binary Strings
// and Print their Binary Sum
#include <stdio.h>
#include <string.h>
// Function to add two Binary Strings
void sum(char b1[], char b2[], int l1, int l2)
{
int carry = 0, temp, num1, num2, i;
char result[100];
result[l1 + 1] = '\0';
// This loop will add Both Strings till
// second have characters in it.
while (l2 > 0) {
num1 = b1[l1 - 1] - '0';
num2 = b2[l2 - 1] - '0';
temp = num1 + num2 + carry;
carry = 0;
if (temp >= 2) {
carry = 1;
temp = temp % 2;
}
result[l1] = temp + '0';
l1--;
l2--;
}
// This loop will add leftover
// characters of first Strings.
while (l1 - 1 >= 0) {
temp = b1[l1 - 1] + carry - '0';
if (temp >= 2) {
carry = 1;
temp = temp % 2;
}
result[l1] = temp + '0';
l1--;
}
// Add last carry to result string
if (carry) {
result[0] = '1';
}
else {
// if there is no carry then we will shift
// each character by one place in left side.
for (i = 0; i < strlen(result) - 1; i++) {
result[i] = result[i + 1];
}
result[strlen(result) - 1] = '\0';
}
// printing result
printf("%s + %s = %s\n", b1, b2, result);
}
// Driver code
int main()
{
char b1[100] = "1001", b2[100] = "1001";
int l1, l2;
printf("Enter binary number 1: ");
printf("%s \n", b1);
printf("Enter binary number 2: ");
printf("%s \n", b2);
l1 = strlen(b1);
l2 = strlen(b2);
// calling function to add strings
if (l1 > l2) {
sum(b1, b2, l1, l2);
}
else {
sum(b2, b1, l2, l1);
}
return 0;
}
OutputEnter binary number 1: 1001
Enter binary number 2: 1001
1001 + 1001 = 10010
The time complexity is O(n), where n is the length of the longer binary string.
The auxiliary space is O(n), where n is the length of the longer binary string.
Method: Using a while loop
C
#include <stdio.h>
int main() {
long binary1=10000, binary2=10000;
int i = 0, remainder = 0, sum[20];
while (binary1 != 0 || binary2 != 0)
{
sum[i++] =(binary1 % 10 + binary2 % 10 + remainder) % 2;
remainder =(binary1 % 10 + binary2 % 10 + remainder) / 2;
binary1 = binary1 / 10;
binary2 = binary2 / 10;
}
if (remainder != 0)
sum[i++] = remainder;
--i;
printf("Sum of two binary numbers: ");
while (i >= 0)
printf("%d", sum[i--]);
return 0;
}
OutputSum of two binary numbers: 100000
The time complexity is O(log n)
The auxiliary space is also O(log n)
Method 3: Bitwise Addition
This approach uses the concept of binary addition to add two binary strings a and b. The steps are as follows:
- Calculate the lengths of both strings a and b using the strlen() function.
- Initialize a variable carry to 0, and two variables i and j to the lengths of the strings minus one.
- Initialize a variable maxLen to the maximum length of the two strings, and allocate memory for a result string of size maxLen + 1 using the malloc() function. Set the last element of the result string to the null character \0.
- While either i or j is greater than or equal to zero, do the following:
- Initialize a variable sum to carry.
- If i is greater than or equal to zero, add the numeric value of the i-th character of a (converted from ASCII to integer using the – ‘0’ expression) to sum and decrement i.
- If j is greater than or equal to zero, add the numeric value of the j-th character of b (converted from ASCII to integer using the – ‘0’ expression) to sum and decrement j.
- Divide sum by 2 using the right shift operator >>, and store the result in carry.
- Set the maxLen-th character of the result string (converted to ASCII using the +’0′ expression) to the least significant bit of sum (obtained using the bitwise AND operator & with 1), and decrement maxLen.
- If there is a final carry after the previous loop, do the following:
- Reallocate memory for the result string to accommodate one extra character using the realloc() function.
- Shift the result string to the right by one using the memmove() function.
- Set the leftmost character of the result string to ‘1’.
- Return the result string.
- Free the memory allocated for the result string using the free() function.
Below is the implementation of the above approach:
C
#include <stdio.h>
#include <string.h>
char *addBinary(char *a, char *b) {
int len1 = strlen(a);
int len2 = strlen(b);
int carry = 0, i = len1-1, j = len2-1;
int maxLen = len1 > len2 ? len1 : len2;
char *result = (char*)malloc((maxLen + 1) * sizeof(char)); // allocate memory for result string
result[maxLen] = '\0';
// add binary digits from right to left
while (i >= 0 || j >= 0) {
int sum = carry;
if (i >= 0) sum += a[i--] - '0';
if (j >= 0) sum += b[j--] - '0';
carry = sum >> 1; // carry is 1 if sum is 2 or greater, 0 otherwise
result[--maxLen] = (sum & 1) + '0'; // set the rightmost bit of result to the sum's least significant bit
}
if (carry) { // if there is a final carry, prepend it to the result
result = (char*)realloc(result, (strlen(result) + 2) * sizeof(char)); // reallocate memory for bigger result string
memmove(result + 1, result, strlen(result) + 1); // shift result string to the right by 1
result[0] = '1'; // set the leftmost bit to 1
}
return result;
}
int main() {
char a[] = "101";
char b[] = "1101";
char *result = addBinary(a, b);
printf("Sum of %s and %s is %s\n", a, b, result);
free(result); // free memory allocated for result string
return 0;
}
OutputSum of 101 and 1101 is 10010
The time complexity of the addBinary function is O(n), where n is the length of the longer input string.
The auxiliary space complexity of the function is also O(n), where n is the length of the longer input string.
Approach: Binary Addition using Bitwise Operations
This approach uses bitwise operators to perform binary addition. It is a more efficient approach compared to the traditional method of converting the binary strings to decimal and then adding them.
Steps:
- Define a constant MAX_LEN to store the maximum length of the binary strings.
- Declare a function addBinary that takes two binary strings as input and returns the resultant binary string.
- Initialize a static character array result of size MAX_LEN to store the resultant binary string.
- Determine the lengths of the binary strings a and b.
- Initialize the carry to 0 and index variables i, j, and k to the lengths of the binary strings a, b, and result minus 1, respectively.
- Loop through the binary strings from right to left until all digits have been added and the carry is 0.
- Compute the sum of the digits and the carry, and add the sum modulo 2 to the result array at index k.
- Update the carry to the sum divided by 2.
- Reverse the result array to get the correct order of digits.
- In the main function, prompt the user to input the binary strings a and b.
- Call the addBinary function to add the binary strings a and b.
- Display the sum of the binary strings to the user.
C
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
// Function to add two binary strings
char* addBinary(char* a, char* b) {
static char result[MAX_LEN]; // Resultant binary string
int len_a = strlen(a);
int len_b = strlen(b);
int carry = 0; // Initialize carry to 0
int i = len_a - 1, j = len_b - 1, k = 0; // Index variables
// Loop through the binary strings from right to left
while (i >= 0 || j >= 0 || carry == 1) {
int sum = carry;
if (i >= 0) sum += a[i--] - '0'; // Convert character to integer
if (j >= 0) sum += b[j--] - '0'; // Convert character to integer
result[k++] = (sum % 2) + '0'; // Convert integer to character
carry = sum / 2;
}
// Reverse the resultant binary string
int len_result = strlen(result);
for (int i = 0; i < len_result / 2; i++) {
char temp = result[i];
result[i] = result[len_result - i - 1];
result[len_result - i - 1] = temp;
}
return result;
}
int main() {
char a[MAX_LEN], b[MAX_LEN];
strcpy(a, "11");
strcpy(b, "11");
printf("The sum of %s and %s is %s\n", a, b, addBinary(a, b));
return 0;
}
OutputThe sum of 11 and 11 is 110
Time Complexity: O(n), where n is the length of the binary strings.
Auxiliary Space: O(n), where n is the length of the binary strings.
Similar Reads
C Program to Add Two Integers
Given two integers, the task is to add these integer numbers and return their sum. Examples Input: a = 5, b = 3Output: 8Explanation: The sum of 5 and 3 is 8. Input: a = -2, b = 7Output: 5Explanation: The sum of -2 and 7 is 5. Add Two Numbers in CIn C, we can add two numbers easily using addition ope
4 min read
C Program to Check for Palindrome String
A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program. The simplest method to check for palindrome string is to reverse the given string and store it in a tem
4 min read
C Program to Compare Two Strings Using Pointers
In C, two strings are generally compared character by character in lexicographical order (alphabetical order). In this article, we will learn how to compare two strings using pointers. To compare two strings using pointers, increment the pointers to traverse through each character of the strings whi
2 min read
Array of Pointers to Strings in C
In C, arrays are data structures that store data in contiguous memory locations. Pointers are variables that store the address of data variables. We can use an array of pointers to store the addresses of multiple elements. In this article, we will learn how to create an array of pointers to strings
2 min read
C Program to Concatenate Two Strings Using a Pointer
Concatenating two strings means appending one string at the end of another string. While the standard library provides strcat() for concatenation, this article will demonstrate how to concatenate two strings using pointers. To concatenate two strings using pointers, traverse the first string to its
1 min read
C program to set K-th bit of a number N
Given a number N and an integer K, the task is to set the Kth bit of the number N, i.e., if the Kth bit is 0, then set it to 1 and if it is 1 then leave it unchanged. Examples: Input: N = 5, K = 2Output: 7Explanation: 5 is represented as 101 in binary and has its second bit 0, so setting it will res
3 min read
Convert Binary to Decimal in C
In this article, we will learn how to write a C program to convert the given binary number into an equivalent decimal number. Binary numbers are expressed in base 2 ( 0, 1 ) and decimal numbers are expressed in base 10 ( 0-9 ). Algorithm to Convert Binary Numbers to DecimalThe idea is to extract the
3 min read
Convert Decimal to Binary in C
In this article, we will learn to write a C program to convert a decimal number into a binary number. The decimal number system uses ten digits from 0 to 9 to represent numbers and the binary number system is a base-2 number system that uses only 0 and 1 to represent numbers. Algorithm to Convert De
2 min read
How to Convert a String to a Char Array in C?
In C, the only difference between the string and a character array is possibly the null character '\0' but strings can also be declared as character pointer in which case, its characters are immutable. In this article, we will learn how to convert a string to a char array in C. The most straightforw
2 min read
How to Reverse a String in C?
In C, a string is a sequence of characters terminated by a null character (\0). Reversing a string means changing the order of the characters such that the characters at the end of the string come at the start and vice versa. In this article, we will learn how to reverse a string in C. Example: Inpu
2 min read