也许您可以利用std::bitset
C++11 中可用的类型。它可以用来表示固定的N
位序列,可以通过常规逻辑进行操作。
#include<iostream>
#include<bitset>
class MissileLauncher {
public:
MissileLauncher() {}
void show_bits() const {
std::cout<<m_abc[2]<<", "<<m_abc[1]<<", "<<m_abc[0]<<std::endl;
}
bool toggle_a() {
// toggles (i.e., flips) the value of `a` bit and returns the
// resulting logical value
m_abc[0].flip();
return m_abc[0];
}
bool toggle_c() {
// toggles (i.e., flips) the value of `c` bit and returns the
// resulting logical value
m_abc[2].flip();
return m_abc[2];
}
bool matches(const std::bitset<3>& mask) {
// tests whether all the bits specified in `mask` are turned on in
// this instance's bitfield
return ((m_abc & mask) == mask);
}
private:
std::bitset<3> m_abc;
};
typedef std::bitset<3> Mask;
int main() {
MissileLauncher ml;
// notice that the bitset can be "built" from a string - this masks
// can be made available as constants to test whether certain bits
// or bit combinations are "on" or "off"
Mask has_a("001"); // the zeroth bit
Mask has_b("010"); // the first bit
Mask has_c("100"); // the second bit
Mask has_a_and_c("101"); // zeroth and second bits
Mask has_all_on("111"); // all on!
Mask has_all_off("000"); // all off!
// I can even create masks using standard logic (in this case I use
// the or "|" operator)
Mask has_a_and_b = has_a | has_b;
std::cout<<"This should be 011: "<<has_a_and_b<<std::endl;
// print "true" and "false" instead of "1" and "0"
std::cout<<std::boolalpha;
std::cout<<"Bits, as created"<<std::endl;
ml.show_bits();
std::cout<<"is a turned on? "<<ml.matches(has_a)<<std::endl;
std::cout<<"I will toggle a"<<std::endl;
ml.toggle_a();
std::cout<<"Resulting bits:"<<std::endl;
ml.show_bits();
std::cout<<"is a turned on now? "<<ml.matches(has_a)<<std::endl;
std::cout<<"are both a and c on? "<<ml.matches(has_a_and_c)<<std::endl;
std::cout<<"Toggle c"<<std::endl;
ml.toggle_c();
std::cout<<"Resulting bits:"<<std::endl;
ml.show_bits();
std::cout<<"are both a and c on now? "<<ml.matches(has_a_and_c)<<std::endl;
std::cout<<"but, are all bits on? "<<ml.matches(has_all_on)<<std::endl;
return 0;
}
使用 gcc 4.7.2 编译
g++ example.cpp -std=c++11
我得到:
This should be 011: 011
Bits, as created
false, false, false
is a turned on? false
I will toggle a
Resulting bits:
false, false, true
is a turned on now? true
are both a and c on? false
Toggle c
Resulting bits:
true, false, true
are both a and c on now? true
but, are all bits on? false