ในส่วนนี้เราจะมาดูกันว่าเราจะหาส่วนเสริมของ 2 ได้อย่างไรโดยใช้การดำเนินการ XOR บนสตริงไบนารี ส่วนเสริมของ 2 อันที่จริงส่วนเสริมของ 1 + 1 เราจะใช้การดำเนินการ XOR เพื่อรับส่วนเสริมของ 1
เราจะข้ามสตริงจาก LSb และมองหา 0 เราจะพลิก 1 ทั้งหมดเป็น 0 จนกว่าเราจะได้ 0 จากนั้นพลิกค่าที่พบ 0
เราจะเดินทางจาก LSb จากนั้นละเว้น 0 ทั้งหมดจนกว่าเราจะได้ 1 ละเว้น 1 ตัวแรก เราจะสลับบิตทั้งหมดโดยใช้การดำเนินการ XOR
อัลกอริทึม
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
ตัวอย่าง
#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);
} ผลลัพธ์
Enter a binary string: 10110110 2's complement of 10110110 is 01001010