C Program to Add Two Binary Strings
C Program to Add Two Binary Strings
A school text exercise needs to add binary strings while preserving the buffer’s valid characters and final terminator.
Add binary digit strings from right to left using a carry, then reverse the produced digits into reading order.
Before this exercise, review strings and their terminator and array bounds. The worked program below applies those ideas to this specific problem.
Explain
Explain why add binary strings uses this sequence of operations.
Trace
Trace the sample values and predict the printed result.
Apply
Try a nonbinary digit and return failure instead of treating it as a larger bit.
Add Binary Strings: follow the data
Given data
A school text exercise needs to add binary strings while preserving the buffer’s valid characters and final terminator.
Rule
Add binary digit strings from right to left using a carry, then reverse the produced digits into reading order.
Observed result
1000
Understand the operation
Each column sums the remaining carry and available input bits. The result bit is sum%2 and the next carry is sum/2. Validation accepts only zero or one for each bit.
A C string ends at its first null character. Read only within its accessible storage and reserve a position for that terminator when producing a changed string. These examples use basic text bytes, not a Unicode grapheme-processing library.
Read the complete C program
The input values are written into this complete C17 example so the calculation can be reproduced without an unavailable service. Change the named data, rebuild and compare the actual output with your prediction.
C17 · complete program
#include <stdio.h>
#include <string.h>
#include <ctype.h>
static int add_binary(const char *left, const char *right, char *out, size_t capacity) {
size_t a = strlen(left), b = strlen(right), used = 0;
int carry = 0;
if (a == 0 || b == 0 || capacity < (a > b ? a : b) + 2) return 0;
while (a != 0 || b != 0 || carry != 0) {
int sum = carry;
if (a != 0) { char digit = left[--a]; if (digit != '0' && digit != '1') return 0; sum += digit - '0'; }
if (b != 0) { char digit = right[--b]; if (digit != '0' && digit != '1') return 0; sum += digit - '0'; }
out[used++] = (char)('0' + sum % 2); carry = sum / 2;
}
for (size_t i = 0; i < used / 2; i++) { char saved = out[i]; out[i] = out[used - 1 - i]; out[used - 1 - i] = saved; }
out[used] = '\0';
return 1;
}
int main(void) {
char result[16];
if (!add_binary("101", "11", result, sizeof result)) { puts("Invalid binary input"); return 0; }
puts(result);
return 0;
}
Expected output
1000
Run in C compiler →Follow the values through the code
C17 · code used in this explanation
#include <stdio.h>
#include <string.h>
#include <ctype.h>
static int add_binary(const char *left, const char *right, char *out, size_t capacity) {
size_t a = strlen(left), b = strlen(right), used = 0;
int carry = 0;
if (a == 0 || b == 0 || capacity < (a > b ? a : b) + 2) return 0;
while (a != 0 || b != 0 || carry != 0) {
int sum = carry;
if (a != 0) { char digit = left[--a]; if (digit != '0' && digit != '1') return 0; sum += digit - '0'; }
if (b != 0) { char digit = right[--b]; if (digit != '0' && digit != '1') return 0; sum += digit - '0'; }
out[used++] = (char)('0' + sum % 2); carry = sum / 2;
}
for (size_t i = 0; i < used / 2; i++) { char saved = out[i]; out[i] = out[used - 1 - i]; out[used - 1 - i] = saved; }
out[used] = '\0';
return 1;
}
int main(void) {
char result[16];
if (!add_binary("101", "11", result, sizeof result)) { puts("Invalid binary input"); return 0; }
puts(result);
return 0;
}
For 101 + 11, the low column produces zero and carry one, the middle produces zero and carry one, and the high column also produces zero and carry one. The remaining carry gives the leading one.
Compare the printed answer with the original text and the stated ordering or filtering rule. The presence of a terminator makes %s usable; it does not by itself make every earlier write fit.
Follow the worked calculation
Start with the sample
For 101 + 11, the low column produces zero and carry one, the middle produces zero and carry one, and the high column also produces zero and carry one. The remaining carry gives the leading one.
Apply the rule
Compare the printed answer with the original text and the stated ordering or filtering rule. The presence of a terminator makes %s usable; it does not by itself make every earlier write fit.
Check the result
1000
1000
Try a small variation
C17 · code used in this explanation
#include <stdio.h>
#include <string.h>
#include <ctype.h>
static int add_binary(const char *left, const char *right, char *out, size_t capacity) {
size_t a = strlen(left), b = strlen(right), used = 0;
int carry = 0;
if (a == 0 || b == 0 || capacity < (a > b ? a : b) + 2) return 0;
while (a != 0 || b != 0 || carry != 0) {
int sum = carry;
if (a != 0) { char digit = left[--a]; if (digit != '0' && digit != '1') return 0; sum += digit - '0'; }
if (b != 0) { char digit = right[--b]; if (digit != '0' && digit != '1') return 0; sum += digit - '0'; }
out[used++] = (char)('0' + sum % 2); carry = sum / 2;
}
for (size_t i = 0; i < used / 2; i++) { char saved = out[i]; out[i] = out[used - 1 - i]; out[used - 1 - i] = saved; }
out[used] = '\0';
return 1;
}
int main(void) {
char result[16];
if (!add_binary("101", "11", result, sizeof result)) { puts("Invalid binary input"); return 0; }
puts(result);
return 0;
}
Try a nonbinary digit and return failure instead of treating it as a larger bit.
Worked answer
The complete worked answer applies the same explicitly bounded operation to a small variation. Read its stored bytes and terminator separately from the visible output.
C17 · complete program
#include <stdio.h>
#include <string.h>
#include <ctype.h>
static int add_binary(const char *left, const char *right, char *out, size_t capacity) {
size_t a = strlen(left), b = strlen(right), used = 0;
int carry = 0;
if (a == 0 || b == 0 || capacity < (a > b ? a : b) + 2) return 0;
while (a != 0 || b != 0 || carry != 0) {
int sum = carry;
if (a != 0) { char digit = left[--a]; if (digit != '0' && digit != '1') return 0; sum += digit - '0'; }
if (b != 0) { char digit = right[--b]; if (digit != '0' && digit != '1') return 0; sum += digit - '0'; }
out[used++] = (char)('0' + sum % 2); carry = sum / 2;
}
for (size_t i = 0; i < used / 2; i++) { char saved = out[i]; out[i] = out[used - 1 - i]; out[used - 1 - i] = saved; }
out[used] = '\0';
return 1;
}
int main(void) {
char result[16];
if (!add_binary("102", "11", result, sizeof result)) { puts("Invalid binary input"); return 0; }
puts(result);
return 0;
}
Expected output
Invalid binary input
Run in C compiler →Recognize the important boundaries
The fixture’s strings are short and capacity includes one possible extra carry digit plus the terminator. A general huge-length contract needs overflow-safe capacity arithmetic.
An untrusted input string needs a verified buffer bound and a valid terminator. strlen is not a safe way to prove arbitrary raw storage has a terminator.
Check your understanding
Choose the answer, then compare the reasoning for every option.
Use the idea independently
Add binary digit strings from right to left using a carry, then reverse the produced digits into reading order.
Continue with character-array storage.
Continue with bounded line reading.
Language reference: WG14 C11 committee draft. These examples use the C17-compatible subset of the explained language features.
Reaching the recap and completing the quizzes are separate milestones.