Write a Program in C++ to find two’s complement of a binary number.
We will ask the user to enter a Binary Number as a string, then the program will find 2’s complement of the given binary number.
2’s complement of a binary number is another binary number that can be find by the addition of 1 to one’s complement(as previously calculated).
Example of binary input: 101010
One’s complement the number: 010110
Example 1:
Binary Value:000100
1s Complement = 111011
2s Complement = 111100
Example 2:
Binary Value: 110101
1s Complement = 001010
2s Complement = 001011
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
//2's complement of a BinaryNumber in C++ [Program] #include <iostream> #define size 6 using namespace std; int main() { char BinaryNumber[size + 1], Complement1[size + 1], Complement2[size + 1]; int i, CarryBits = 1, fail = 0; cout << " Input a " << size << " bit BinaryNumber: "; cin >> BinaryNumber; for (i = 0; i < size; i++) { if (BinaryNumber[i] == '1') { Complement1[i] = '0'; } else if (BinaryNumber[i] == '0') { Complement1[i] = '1'; } else { cout << "Sorry, its Error! Please Input the number of assigned bits." << endl; fail = 1; break; } } Complement1[size] = '\0'; for (i = size - 1; i >= 0; i--) { if (Complement1[i] == '1' && CarryBits == 1) { Complement2[i] = '0'; } else if (Complement1[i] == '0' && CarryBits == 1) { Complement2[i] = '1'; CarryBits = 0; } else { Complement2[i] = Complement1[i]; } } Complement2[size] = '\0'; if (fail == 0) { cout << " The original BinaryNumber = " << BinaryNumber << endl; cout << " After 1s complement the value = " << Complement1 << endl; cout << " After 2s complement the value = " << Complement2 << endl; } } |