93 lines
1.5 KiB
C
93 lines
1.5 KiB
C
#include<stdlib.h>
|
|
#include<string.h>
|
|
|
|
size_t max(size_t a, size_t b) {
|
|
if (a > b) return a;
|
|
return b;
|
|
}
|
|
|
|
char* addBinary(char *a, char *b) {
|
|
// Get length of strings
|
|
size_t l_a = strlen(a)+1;
|
|
size_t l_b = strlen(b)+1;
|
|
|
|
// Final string length
|
|
size_t l_x = max(l_a, l_b)+1;
|
|
|
|
// Create buffer
|
|
char* outString = malloc(l_x);
|
|
|
|
// String end
|
|
outString[l_x-1] = 0;
|
|
// Index variable from end
|
|
size_t i = 1;
|
|
|
|
// Index variables of a, b
|
|
size_t ai = 1;
|
|
size_t bi = 1;
|
|
|
|
uint8_t carry = 0;
|
|
uint8_t tempSum = 0;
|
|
|
|
// Do a sum
|
|
do {
|
|
// Increment all our indices
|
|
ai++;
|
|
bi++;
|
|
i++;
|
|
|
|
// Full adder logic for a_i, b_i, carry.
|
|
char c_a = a[l_a-ai];
|
|
char c_b = b[l_b-bi];
|
|
|
|
// Use XOR operator to add bits.
|
|
tempSum = c_a^c_b^carry;
|
|
|
|
// Calculate carry (we only care about the 1st bit)
|
|
carry = ((c_a^c_b)&carry) | (c_a&c_b);
|
|
|
|
// Create char that holds sum.
|
|
char c = (tempSum & 1) ^ '0';
|
|
|
|
// Store into output
|
|
outString[l_x-i] = c;
|
|
} while (ai < l_a && bi < l_b);
|
|
|
|
// Still more in a.
|
|
while (ai < l_a) {
|
|
ai++;
|
|
i++;
|
|
|
|
// Half adder
|
|
char ca = a[l_a-ai];
|
|
tempSum = ca^carry;
|
|
carry = ca & carry;
|
|
|
|
char c = (tempSum & 1) ^ '0';
|
|
outString[l_x-i] = c;
|
|
}
|
|
|
|
// Still more in b.
|
|
while (bi < l_b) {
|
|
bi++;
|
|
i++;
|
|
|
|
// Half adder
|
|
char cb = b[l_b-bi];
|
|
tempSum = cb^carry;
|
|
carry = cb & carry;
|
|
char c = (tempSum & 1) ^ '0';
|
|
outString[l_x-i] = c;
|
|
}
|
|
|
|
// Include the final carry bit.
|
|
if (carry&1) {
|
|
i++;
|
|
outString[l_x-i] = '1';
|
|
}
|
|
|
|
// Return string.
|
|
return &outString[l_x-i];
|
|
}
|
|
|