# 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.

## 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
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

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) {
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
{"ft_lang_label":"__label__en","ft_lang_prob":0.590187,"math_prob":0.96758467,"size":1469,"snap":"2022-05-2022-21","text_gpt3_token_len":434,"char_repetition_ratio":0.13037543,"word_repetition_ratio":0.006688963,"special_character_ratio":0.34717494,"punctuation_ratio":0.13271604,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9895995,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-05-18T01:25:38Z\",\"WARC-Record-ID\":\"<urn:uuid:809efd24-47bf-4997-bf18-acc799932581>\",\"Content-Length\":\"32352\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:044d7fbb-c5b0-4155-8cce-32c487d5d815>\",\"WARC-Concurrent-To\":\"<urn:uuid:f22119dc-3dc3-43b4-abf9-14ab43d6ac5a>\",\"WARC-IP-Address\":\"192.229.210.176\",\"WARC-Target-URI\":\"https://www.tutorialspoint.com/2-s-compliment-for-a-given-string-using-xor\",\"WARC-Payload-Digest\":\"sha1:OLK2IZ5CQYNG5K5EZWRXZ2XTOFMIXGCZ\",\"WARC-Block-Digest\":\"sha1:QBTRF5GRAHKRZJLDYH2VHRHEHY7II2SJ\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-21/CC-MAIN-2022-21_segments_1652662520936.24_warc_CC-MAIN-20220517225809-20220518015809-00234.warc.gz\"}"}