Given a binary number, return the 1’s and 2’s complement of that number.

Before getting into programming, we shall look at how to get 1’s and 2’s complement of a given binary number.

## 1’s Complement:

1’s complement of a number is achieved by flipping all the bits.

### Example:

Original value 1’s Complement

0 1

1 0

1100 0011

1111 0000

## 2’s complement:

We get the 2’s complement, by adding 1 to the 1’s complement of the binary number.

2’s complement = 1’s complement + 1;

2’s complement is particularly important because, it is used to represent signed (-ve) numbers in binary. Positive number are stored as it is, but negative number will be stored in 2’s complement.

### Example:

Original Value 1’s complement 2’s complement

10011001 01100110 +1 = 01100111

## So how 2’s complement is used to represent –ve number ?

For example, we take -5 to represent it in a binary format.

Convert 5 to binary format “00000101”

1’s complement “11111010” then add “1” for 2’s complement.

2’s complement “11111011”

To recalculate it into decimal:

-128 + 64 + 32 + 16 + 8 + 2 + 1 = -5

### OK, now coming back to our question:

To get the 1’s complement, we flip the bits.

To get 2’c complement, flip all 1’s to 0 till me encounter first 0, then flip that 0 to 1.

### Example:

Binary number is 1100

Then, 1’s complement is 0011

### For 2’s complement:

Step 1: flip all the 1’s to 0 as: “0000”

Step 2: then flip first occurrence of 0 to 1 as “0100” gives us 2’s complement.

Note: The first occurrence of 0 is in the index 3 of 1’s complement.

## Solution in C++

/* * File : ones_twos_complement.cpp * Contact : ajay.thousand@gmail.com * Website: @ prodevelopertutorial.com */ #include<iostream> #include<vector> #include<string> using namespace std; char flip(char c) { if(c == '0') return '1'; else return '0'; } void get_ones_twos_complement(string str) { int len = str.size(); string ones ; string twos ; for(int i = 0; i <len; i++ ) { ones += flip(str[i]); } cout << "1's complement: " << ones << endl; twos = ones; int i = 0; for ( i = len - 1; i > 0; i--) { if(ones[i] == '1') twos[i] = '0'; else { twos[i] = '1'; break; } } // This case is used to handle situations like "1111" // we add extra "1" on the left side if (i == -1) twos = '1'+twos; cout << "2's complement: " << twos << endl; } int main() { string binary = "1100"; cout<<"Original binary number = "<<binary<<endl; get_ones_twos_complement(binary); return 0; }

### Output:

Original binary number = 1100 1's complement: 0011 2's complement: 0100