📝📚Intermediate

Add 2 Binary Strings

Binary string addition

Add two binary strings and return the sum as a binary string.

Program Code

add_binary_strings.c
C
1#include <stdio.h>
2#include <string.h>
3
4void addBinary(char a[], char b[], char result[]) {
5 int lenA = strlen(a);
6 int lenB = strlen(b);
7 int i = lenA - 1, j = lenB - 1;
8 int carry = 0, k = 0;
9 char temp[100];
10
11 while (i >= 0 || j >= 0 || carry) {
12 int sum = carry;
13
14 if (i >= 0) {
15 sum += a[i] - '0';
16 i--;
17 }
18 if (j >= 0) {
19 sum += b[j] - '0';
20 j--;
21 }
22
23 temp[k++] = (sum % 2) + '0';
24 carry = sum / 2;
25 }
26
27 // Reverse the result
28 for (int m = 0; m < k; m++) {
29 result[m] = temp[k - 1 - m];
30 }
31 result[k] = '\0';
32}
33
34int main() {
35 char a[] = "1010";
36 char b[] = "1011";
37 char result[100];
38
39 addBinary(a, b, result);
40
41 printf(" %s\n", a);
42 printf("+ %s\n", b);
43 printf("------\n");
44 printf(" %s\n", result);
45
46 return 0;
47}
Output

1010

+ 1011

------

10101