Is there way to use a boolean in C++ as a bitmap? [closed]
Is there way to use a boolean in C++ as a bitmap?
Code example:
bool boolean = false;
boolean &a开发者_如何学运维mp;= ~(1 << 0);
boolean |= 1 << 2;
boolean |= 1 << 1;
cout << "boolean : " << boolean << endl;
bool bit1 = boolean & (1 << 2);
bool bit2 = boolean & (1 << 1);
bool bit3 = boolean & (1 << 0);
cout << "bit1 : " << bit1 << endl;
cout << "bit2 : " << bit2 << endl;
cout << "bit3 : " << bit3 << endl;
Output:
boolean : 1
bit1 : 0
bit2 : 0
bit3 : 1
Are you possibly thinking of something like std::bitset
?
A bitset is a special container class that is designed to store bits (elements with only two possible values: 0 or 1,
true
orfalse
, ...).The class is very similar to a regular array, but optimizing for space allocation: each element occupies only one bit (which is eight times less than the smallest elemental type in C++:
char
).Each element (each bit) can be accessed individually: for example, for a given bitset named
mybitset
, the expressionmybitset[3]
accesses its fourth bit, just like a regular array accesses its elements.
Update
In your code example, you are using (or abusing) the fact the boolean instances are in practice represented as integer-type values of at least 1 byte, thus 8 bits in size (the standard probably defines this more precisely).
So in practice you can do bit-flipping in a bool
value, but my bet is that the result is undefined. And even if not, it is highly unusual, thus hard to understand and maintain by others. So you would better use standard int
s for such purposes.
精彩评论