Considering that two bitsets are provided in the form of strings, char a[]
and char b[]
, as in the code below. And the task of add that bitsets is given. I take it and wrote the following to sum the two bitsets:
#include <stdio.h>
#include <string.h>
int carry = 0;
char result(char r, int c) {
char R = '0';
if (carry) {
if (c) {
R = '0';
carry = 1;
} else {
R = r == '0' ? '1' : '0';
carry = R == '0' ? 1 : 0;
}
} else {
if (c) {
R = '0';
carry = 1;
} else {
R = r;
carry = 0;
}
}
return R;
}
char sum(int x, int y) {
char r = '0';
if (x ^ y)
r = result('1', 0);
else if (x & y)
r = result('0', 1);
else
r = result('0', 0);
return r;
}
int main() {
char a[] = "01";
char b[] = "01";
char c[] = "00";
for (int i = strlen(c)-1; i > -1; i--)
c[i] = sum(a[i] == '0' ? 0 : 1, b[i] == '0' ? 0 : 1);
printf("%s\n", c);
}
Is it possible to make it simpler?
a
andb
guaranteed to be the same length? What about if the top bit carries? Shouldc
be extended by 1 character? \$\endgroup\$