## Wednesday, May 24, 2017

### Bitwise Operators

* Write an "app" that takes two bit strings and returns (display) OR, AND, XOR of the two strings

Desire Output

#include<bits/stdc++.h>
#include <iostream>
using namespace std;

//adds the two bit strings and return the result
string orOperation( string first, string second );

int makeLegnthEqual(string &str1, string &str2)
{
int len1 = str1.size();
int len2 = str2.size();
if (len1 < len2)
{
for (int i = 0 ; i < len2 - len1 ; i++)
str1 = '0' + str1;
return len2;
}
else if (len1 > len2)
{
for (int i = 0 ; i < len1 - len2 ; i++)
str2 = '0' + str2;
}
return len1; // If len1 >= len2
}

// The main function that adds two bit sequences and returns the addition
string orOperation( string first, string second )
{
string result; // To store the sum bits

// make the lengths same before adding
int length = makeLegnthEqual(first, second);

// Add all bits one by one
for (int i = length-1 ; i >= 0 ; i--)
{
int firstBit = first.at(i) - '0';
int secondBit = second.at(i) - '0';

// boolean expression for sum of 3 bits
int sum = (firstBit | secondBit)^'0';

result = (char)sum + result;
}

return result;
}
string andOperation( string first, string second )
{
string result; // To store the sum bits

// make the lengths same before adding
int length = makeLegnthEqual(first, second);

// Add all bits one by one
for (int i = length-1 ; i >= 0 ; i--)
{
int firstBit = first.at(i) - '0';
int secondBit = second.at(i) - '0';

// boolean expression for sum of 3 bits
int sum = (firstBit & secondBit)^'0';

result = (char)sum + result;
}

return result;
}
string xorOperation( string first, string second )
{
string result; // To store the sum bits

// make the lengths same before adding
int length = makeLegnthEqual(first, second);

// Add all bits one by one
for (int i = length-1 ; i >= 0 ; i--)
{
int firstBit = first.at(i) - '0';
int secondBit = second.at(i) - '0';

// boolean expression for sum of 3 bits
int sum = (firstBit ^ secondBit)^'0';

result = (char)sum + result;
}

return result;
}

// Driver program to test above functions
int main()
{
string str1 = "";
string str2 = "";
cout<<"Please, enter the first string value"<<endl;
cin>>str1;
cout<<"Please, enter the second string value"<<endl;
cin>>str2;

cout << "OR operation value  is: " << orOperation(str1, str2)<<endl;
cout << "AND operation value is: " << andOperation(str1, str2)<<endl;
cout << "XOR operation value is " << xorOperation(str1, str2)<<endl;

return 0;
}