2’s compliment for a givin string using XOR

Given a binary string, task is to convert this string in to two’s compliment with the help of XOR operator.

Examples:

Input : 00000101
Output :11111011

Input : 10010
Output : 01110


We have discussed an approach in previous post to find 2’s complement

For 2’s complement, we first find one’s complement. We traverse the one’s complement starting from LSB (least significant bit), and look for 0. We flip all 1’s (change to 0) until we find a 0. Finally, we flip the found 0.

We traverse from the last bot and keep ignoring all 0s until we find a 1. We ignore first 1 also. Then we toggle all bits by doing XOR with 1.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find 2's complement using XOR.
#include <bits/stdc++.h>
using namespace std;
  
string TwoscomplementbyXOR(string str)
{
    int n = str.length();
  
    // A flag used to find if a 1 bit is seen
    // or not.
    bool check_bit = 0;
  
    for (int i = n - 1; i >= 0; i--) {
        if (str[i] == '0' && check_bit == 0) {
            continue;
        }
        else {
  
            // xor operator is used to flip the  
            if (check_bit == 1)
                str[i] = (str[i] - '0') ^ 1 + '0'
  
            // bits after converting in to
            // ASCII values
            check_bit = 1;
        }
    }
  
    // if there is no 1 in the string so just add 
    // 1 in starting of string and return
    if (check_bit == 0) 
        return "1" + str; 
    else
        return str;
}
  
// Driver code
int main()
{
    string str = "101";
    cout << TwoscomplementbyXOR(str);
    return 0;
}

chevron_right


PHP

= 0; $i–)
{
if ($str[$i] == ‘0’ &&
$check_bit == 0)
{
continue;
}
else
{

// xor operator is used
// to flip the
if ($check_bit == 1)
$str[$i] = ($str[$i] – ‘0’) ^ 1 + ‘0’;

// bits after converting in to
// ASCII values
$check_bit = 1;
}
}

// if there is no 1 in the string
// so just add 1 in starting of
// string and return
if ($check_bit == 0)
return “1” + $str;
else
return $str;
}

// Driver code
$str = “101”;
echo TwoscomplementbyXOR($str);

// This code is contributed by akt_mit
?>

Output:

011


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : jit_t