2’s compliment for a given string using XOR ?

CServer Side ProgrammingProgramming

In this section we will see how we can find the 2’s complement using the XOR operation on a binary string. The 2’s complement is actually the 1’s complement + 1. We will use XOR operation to get the 1’s complement.

We will traverse the string from LSb, and look for 0. We will flip all 1’s to 0 until we get a 0. Then flip the found 0.

We will traverse from LSb. Then ignoring all 0’s until we get 1. Ignoring the first 1, we will toggle all bits using the XOR operation.



   len := length of the binary string
   flag := false
   for i := len-1 down to 0, do
      if bin[i] is 0, and flag is not set, then
         ignore the next part, jump to next iteration
         if flag is set, then
            bin[i] := flip of bin[i]
         end if
         flag := true
      end if
   if the flag is not set, then
      attach 1 with bin and return
      return bin
   end if


 Live Demo

#include <iostream>
using namespace std;
string get2sComplement(string bin) {
   int n = bin.length();
   bool flag = false; //flag is used if 1 is seen
   for (int i = n - 1; i >= 0; i--) { //traverse from last bit
      if (bin[i] == '0' && !flag) {
      } else {
         if (flag)
            bin[i] = (bin[i] - '0') ^ 1 + '0'; //flip bit using XOR, then convert to ASCII
         flag = true;
   if (!flag) //if no 1 is there, just insert 1
      return "1" + bin;
      return bin;
int main() {
   string str;
   cout << "Enter a binary string: ";
   cin >> str;
   cout << "2's complement of " << str <<" is " << get2sComplement(str);


Enter a binary string: 10110110
2's complement of 10110110 is 01001010
Published on 24-Jul-2019 11:59:20