Problem – Binary Number as a string, we have to print its 2’s complement.
2’s complement of a binary number is another binary number obtained by adding 1 to one’s complement.
Example:
Input: 101010
One’s complement the number: 010110
Algorithm:
- Take binary number input as string having length say size.
- Initialise int fail=0.
- Start loop from i=0 to i<size
if binary[i]==1
then one[i]=0
else if binary[i]==0
then one[i]=1
else
print “error! Enter binary number of assigned size”
fail=1
break - Put null character in the string complement
one[size] = ‘\0’ - If fail ==0 then print the ones complement.
-
Start loop from i = size – 1 to i >= 0.
if (one[i] == ‘1’ && carry == 1)
two[i] = ‘0’;
else if (one[i] == ‘0’ && carry == 1)
two[i] = ‘1’;
carry = 0;
else
two[i] = one[i]; - Put null character in the string two.
two[size] = ‘\0’; - if fail == 0
then print two’s complement.
Code:
//Program to find two's complement of a binary number
#include <iostream>
#define size 6
using namespace std;
int main() {
char binary[size + 1], one[size + 1], two[size + 1];
int i, carry = 1, fail = 0;
cout << " Input a " << size << " bit binary number: ";
cin >> binary;
for (i = 0; i < size; i++) {
if (binary[i] == '1') {
one[i] = '0';
} else if (binary[i] == '0') {
one[i] = '1';
} else {
cout << "Error! Input the number of assigned bits." << endl;
fail = 1;
break;
}
}
one[size] = '\0';
for (i = size - 1; i >= 0; i--) {
if (one[i] == '1' && carry == 1) {
two[i] = '0';
} else if (one[i] == '0' && carry == 1) {
two[i] = '1';
carry = 0;
} else {
two[i] = one[i];
}
}
two[size] = '\0';
if (fail == 0) {
cout << " The original binary = " << binary << endl;
cout << " After ones complement the value = " << one << endl;
cout << " After twos complement the value = " << two << endl;
}
}
Report Error/ Suggestion