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
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
C Program to Add 2 Binary Strings
Next article icon

C Program to Add 2 Binary Strings

Last Updated : 12 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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; } 

Output
Enter 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; } 

Output
Sum 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; } 

Output
Sum 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:

  1. Define a constant MAX_LEN to store the maximum length of the binary strings.
  2. Declare a function addBinary that takes two binary strings as input and returns the resultant binary string.
  3. Initialize a static character array result of size MAX_LEN to store the resultant binary string.
  4. Determine the lengths of the binary strings a and b.
  5. 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.
  6. Loop through the binary strings from right to left until all digits have been added and the carry is 0.
  7. Compute the sum of the digits and the carry, and add the sum modulo 2 to the result array at index k.
  8. Update the carry to the sum divided by 2.
  9. Reverse the result array to get the correct order of digits.
  10. In the main function, prompt the user to input the binary strings a and b.
  11. Call the addBinary function to add the binary strings a and b.
  12. 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; } 

Output
The 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.


Next Article
C Program to Add 2 Binary Strings

P

pushpamkjha14
Improve
Article Tags :
  • C Programs
  • C Language
  • C Basic Programs

Similar Reads

    C Program to Add Two Integers
    Given two integers, the task is to add these integer numbers and return their sum.ExamplesInput: 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.In C, we have multiple methods to add two numbers, such as the addition operat
    3 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 whil
    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 n
    1 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
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