寻找一些操作员(我猜是代替+?)来做
unsigned char bits = true + false + true + true + true; // 1 byte is sufficient
成为以下位模式:
00010111
然后我如何检查if
中的位模式if (bits == 00010111)
答案 0 :(得分:6)
你想要
bits = true << 5 | false << 4 | true << 3 | true << 2 | true << 1;
或
bits |= true;
bits <<= 1;
bits |= false;
bits <<= 1;
bits |= true;
bits <<= 1;
bits |= true;
bits <<= 1;
bits |= true;
答案 1 :(得分:3)
您可以使用std::bitset
的字符串构造函数。
#include <bitset>
#include <string>
#include <iostream>
int main() {
std::string bits;
bits.push_back('1');
bits.push_back('0');
bits.push_back('1');
bits.push_back('1');
bits.push_back('1');
std::bitset<8> bitset(bits);
std::cout << bitset.to_string();
}
虽然有更好的方法可以做到这一点。
答案 2 :(得分:2)
为什么不使用bitset。有一种方法可以设置各种位并转换为无符号长整型。只需在其上运行一个&
运算符即可得到该字节。
答案 3 :(得分:2)
运算符+需要在当前值的一位左移,然后“按位或”输入true或false并返回。
这是我提出的一个快速实现:
#include <iostream>
class Foo
{
int result;
public:
Foo() : result(0) {}
Foo(bool value) : result(value ? 1 : 0) {}
explicit Foo(int value) : result(value) {}
Foo operator+(bool value) const
{
std::cout << "adding " << value << std::endl;
return Foo((result << 1) | (value ? 1 : 0));
}
int get_result() const { return result; }
};
int main()
{
Foo x;
x = Foo(true) + false + true;
std::cout << x.get_result() << std::endl;
}
使用它here