Teena
Teena

Reputation: 85

OR operation on binary strings in c giving half output as wrong

int stringXor(char *str1,char *str2)
{
    int num1=0,num2=0;
    for (int i = 0; i<strlen(str1); i++)
    {
        num1=str1[i]-'0';
        num2=str2[i]-'0';
        num1 = num1 | num2;
        str1[i]=(char)num1;
        //printf("%d",str1[i]);
    }

    int count=0;
    for(int j=0;j<strlen(str1);j++)
    {
        if(str1[j]==1)
            count++;
    }
    return count;
}

I don't know what the error is, but or operation is not successful on each char of the string.

Upvotes: 0

Views: 67

Answers (1)

Bob Kaufman
Bob Kaufman

Reputation: 12835

If you want a function that will return the number of positions that contain a 1 in either string, consider writing a simpler function that does just that. For example:

int CountOnes( char *str1, char *str2 )
{
    int count = 0;
    int len = strlen( str1 );  // we assume that strlen(str1) == strlen(str2)

    for ( int i = 0; i < len; i++ )
    {
        if ( str1[ i ] == '1' || str2[ i ] == '1' )
            count++;
    }

    return count;
}

Note that this function will not include the side effect of changing str1 as yours currently does.

To store the resulting OR'd string to str1, change the line

if ( str1[ i ] == '1' || str2[ i ] == '1' )

to

str1[ i ] = ( ( str1[ i ] - '0' ) | ( str2[ i ] - '0' ) ) + '0';
if ( str1[ i ] == '1' )
    count++;

Upvotes: 1

Related Questions