如何使用按位異或對給定字串計算 2 進位制補碼?
在本部分,我們將瞭解如何對二進位制字串使用按位異或運算來查詢 2 進位制補碼。2 進位制補碼實際上就是 1 進位制補碼 + 1。我們將使用按位異或運算來獲取 1 進位制補碼。
我們將從 LSB 開始遍歷字串並查詢 0。我們將把所有 1 翻轉為 0,直到獲得 0。然後翻轉找到的 0。
我們將從 LSB 開始遍歷。然後忽略所有 0,直到獲得 1。忽略第一個 1,我們將使用按位異或運算切換所有位。
演算法
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
廣告