c++ - 如何使用位掩码?

标签 c++ c++11 bitmask

如何在 C++ 中使用它?什么时候有用?

使用位掩码查看其实际工作方式的问题示例是什么?

最佳答案

简而言之,位掩码有助于操纵多个值的位置。这里有一个很好的例子;

位标志是一种在一个变量中存储多个不互斥的值的方法。你可能以前见过他们。每个标志都是一个位位置,可以设置为开或关。然后你有一堆位掩码#defined 为每个位位置,所以你可以很容易地操纵它:

    #define LOG_ERRORS            1  // 2^0, bit 0
    #define LOG_WARNINGS          2  // 2^1, bit 1
    #define LOG_NOTICES           4  // 2^2, bit 2
    #define LOG_INCOMING          8  // 2^3, bit 3
    #define LOG_OUTGOING         16  // 2^4, bit 4
    #define LOG_LOOPBACK         32  // and so on...

// Only 6 flags/bits used, so a char is fine
unsigned char flags;

// Initialising the flags,
// Note that assigning a value will clobber any other flags, so you
// it should generally only use the = operator when initialising variables.
flags = LOG_ERRORS;
// Sets to 1 i.e. bit 0

// Initialising to multiple values with OR (|)
flags = LOG_ERRORS | LOG_WARNINGS | LOG_INCOMING;
// sets to 1 + 2 + 8 i.e. bits 0, 1 and 3

// Setting one flag on, leaving the rest untouched
// OR bitmask with the current value
flags |= LOG_INCOMING;

// Testing for a flag
// AND with the bitmask before testing with ==
if ((flags & LOG_WARNINGS) == LOG_WARNINGS)
   ...

// Testing for multiple flags
// As above, OR the bitmasks
if ((flags & (LOG_INCOMING | LOG_OUTGOING))
         == (LOG_INCOMING | LOG_OUTGOING))
   ...

// Removing a flag, leaving the rest untouched
// AND with the inverse (NOT) of the bitmask
flags &= ~LOG_OUTGOING;

// Toggling a flag, leaving the rest untouched
flags ^= LOG_LOOPBACK;

**

WARNING: DO NOT use the equality operator (i.e. bitflags == bitmask) for testing if a flag is set - that expression will only be true if that flag is set and all others are unset. To test for a single flag you need to use & and == :

**

if (flags == LOG_WARNINGS) //DON'T DO THIS
   ...
if ((flags & LOG_WARNINGS) == LOG_WARNINGS) // The right way
   ...
if ((flags & (LOG_INCOMING | LOG_OUTGOING)) // Test for multiple flags set
         == (LOG_INCOMING | LOG_OUTGOING))
   ...

您也可以搜索C++ Tricks .

关于c++ - 如何使用位掩码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18591924/

相关文章:

c++ - 什么是 "template<class T> using owner = T;"?

从 16 位架构中的给定索引计算位掩码

c - 编写一个变量宏,它在一个整数中设置特定位(位掩码)

c# - 在 C# 中获取整数的高字节和低字节并将其作为 char 数组发送到 com 端口,如何?

c# - 在托管代码中调用 SSE 代码(对齐)

C++ unordered_map 错误

c++ - 在 Qt C++ 中连接用户特定的 DBus session

c++ - NameSpaces 何时、何地、为什么!

c++ - 为什么 constexpr 不能应用于构造函数?

c++ - std::unordered_set 如何避免迭代中每个元素上潜在的页面错误?