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.
Algorithm
get2sComp(bin)
begin 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 else if flag is set, then bin[i] := flip of bin[i] end if flag := true end if done if the flag is not set, then attach 1 with bin and return else return bin end if end
Example
#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) { continue; } 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; else return bin; } int main() { string str; cout << "Enter a binary string: "; cin >> str; cout << "2's complement of " << str <<" is " << get2sComplement(str); }
Output
Enter a binary string: 10110110 2's complement of 10110110 is 01001010