檢測C中的匹配位
例如,我正在嘗試使用兩個位元物件
a = 10010111 b = 01110010
並且如果它們在相同的位置/索引中匹配,則從兩個變數中刪除位.所以我們會留下來
a = 100xx1x1 = 10011 b = 011xx0x0 = 01100
有沒有辦法實現這一點?
>為了結果,然後使用push_back可以動態建立bitset.
#include <iostream> #include <boost/dynamic_bitset.hpp> #include <bitset> int main() { const int N = 8; boost::dynamic_bitset<> a_out(0); boost::dynamic_bitset<> b_out(0); std::bitset<N>a(0x97); //10010111 std::bitset<N>b(0x72); //01110010 for (int i = 0; i < N; i++) { if (a[i] != b[i]) { a_out.push_back(bool(a[i])); b_out.push_back(bool(b[i])); } } std::cout << a_out << "\n"; std::cout << b_out << "\n"; return 0; }
ofollow,noindex" target="_blank">Try here!
Output:1001101100
[EDITED]
如果你想優化你可以在for迴圈之前新增(但是你必須有1.62或更高版本才能使用reserve())
//@5gon12eder Optimization const auto xorified = a ^ b; const auto n = xorified.count(); a_out.reserve(n); b_out.reserve(n);
在for迴圈內比較位為:
if (xorified[i]) { ... }
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/41720249/detecting-matching-bits-in-c