I need to 2 strings (10-bit binary numbers). I's easy when i'm adding 1 0 0 0 But how I can modify this, to situation when i'll need to make 11-bit like 1010101010 1111111111=11010101001
i = MAX 1;
while( i!=0) {
if ((str1[i - 1] == str2[i - 1]) && (str1[i - 1] == '0' )) {
str3[i] = '0';
}
else if ((str1[i - 1] != str2[i - 1])) {
str3[i] = '1';
}
else if ((str1[i - 1] == str2[i - 1]) && (str1[i - 1] == '1')) {
str3[i] = '0';
}
i--;
}
MAX=10
CodePudding user response:
#define ADDCHAR(c1,c2) (((c1) == '1') ((c2) == '1'))
char *add(char *res, const char *n1, const char *n2)
{
size_t ln1 = strlen(n1);
size_t ln2 = strlen(n2);
char *resend = res (ln2 > ln1 ? ln2 2 : ln1 2);
unsigned rem = 0;
*resend-- = 0;
while(ln1 || ln2)
{
unsigned pres = rem ADDCHAR(ln1 ? n1[ln1 - 1] : '0', ln2 ? n2[ln2 - 1] : '0');
*resend-- = '0' (pres & 1);
rem = pres >> 1;
ln1 -= !!ln1;
ln2 -= !!ln2;
}
if(rem) *resend-- = '0' rem;
while(resend >= res) *resend-- = ' ';
return res;
}
CodePudding user response:
int a = 0 ;
for(int i = 0 ; i < 10 ; i ){
str3[i] = str1[i] str2[i] a ;
if(str3[i] > 1){
str3[i] %= 2 ;
a = 1 ;
}
else{
a = 0 ;
}
} `
enter code here
enter code here
}
CodePudding user response:
It's not clear exactly what the requirements are, but I wrote a function that takes three strings, figures out their lengths using strlen
, and then sets the third string equal to the sum of the first two. Here is a program that adds the two 10-bit numbers you gave and prints the expected result of "11010101001".
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void binary_string_add(const char * a, const char * b, char * sum)
{
size_t alen = strlen(a);
size_t blen = strlen(b);
size_t sumlen = strlen(sum);
int carry = 0;
for (size_t i = 0; i < sumlen; i )
{
if (i < alen) { carry = a[alen - 1 - i] == '1'; }
if (i < blen) { carry = b[blen - 1 - i] == '1'; }
sum[sumlen - 1 - i] = '0' (carry & 1);
carry >>= 1;
}
}
int main()
{
char str1[] = "1010101010";
char str2[] = "1111111111";
char str3[] = "xxxxxxxxxxx";
binary_string_add(str1, str2, str3);
printf("Sum: %s\n", str3);
}
By the way, each iteration of the loop actually implements a 1-bit adder.
Update: If you want an easier interface that allocates an output string for you of the appropriate length and returns it, this works:
char * binary_string_add2(const char * a, const char * b)
{
size_t alen = strlen(a);
size_t blen = strlen(b);
size_y sumlen = (alen > blen ? alen : blen) 1;
char * sum = malloc(sumlen 1);
if (sum == NULL) { /** Add error handling here. **/ }
memset(sum, 'x', sumlen);
sum[sumlen] = 0;
binary_string_add(a, b, sum);
return sum;
}