开发者

Is there way to use a boolean in C++ as a bitmap? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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 or false, ...).

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 expression mybitset[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 ints for such purposes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜