2's complement in C++

Program to find two’s complement of a binary number in C++

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:

  1. Take a binary number input as a string of length size.
  2. Initialize an integer fail to 0.
  3. Start a loop from i = 0 to i < size.
    1. If binary[i] is equal to 1, set one[i] to 0.
    2. Else, if binary[i] is equal to 0, set one[i] to 1.
    3. Else, print an error message and set fail to 1. Break out of the loop.
  4. Place a null character at the end of the string one.
  5. If fail is equal to 0, print the one's complement.
  6. Start a loop from i = size - 1 to i >= 0.
    1. If one[i] is equal to 1 and carry is equal to 1, set two[i] to 0.
    2. Else, if one[i] is equal to 0 and carry is equal to 1, set two[i] to 1 and set carry to 0.
    3. Else, set two[i] to one[i].
  7. Place a null character at the end of the string two.
  8. If fail is equal to 0, print the 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;
   }
}

Output

Input a 6 bit binary number: 101101
The original binary = 101101
After ones complement the value = 010010
After twos complement the value = 010011

2's complement in C++