函数参数中的按位或(|)

Dar*_*ast 10 c c++ bit-manipulation

我想知道如何做到这一点:

func(param1|param2|param3)
Run Code Online (Sandbox Code Playgroud)

然后在函数中提取这些值,我在多个函数中看到过这个,或者这样做更好:

func(param1, ...)
Run Code Online (Sandbox Code Playgroud)

我试图用C++做到这一点,我正在考虑将函数的参数作为枚举中的值.

我该如何解决这个问题?

Raf*_*cki 17

Param1,param2,param3通常被定义为打开不同位的数字. |是按位替代的运算符,这意味着它在单独的位上工作.

例如:

const int param1 = 0x01;
const int param2 = 0x02;
const int param3 = 0x04;
Run Code Online (Sandbox Code Playgroud)

当你将一个参数传递给函数时,你可以选择先前定义的参数.在函数中,您不进行分解,而是使用按位连接检查是否设置了指定位:

void func(int arg){
  if(arg & param1)
    // do something
  if(arg & param2)
    // do something else
    // ...
}

func(param1 | param3); 
// "do something" will be done,
// but "do something else" not.
Run Code Online (Sandbox Code Playgroud)


pax*_*blo 13

假设您将值作为独立位(2的幂),如:

#define IS_ON    0x01
#define IS_LARGE 0x02
#define IS_RED   0x04
Run Code Online (Sandbox Code Playgroud)

(或等效enumsconst int值,取决于你想要怎么做 - 我之所以使用#define它只是因为它是我习惯的),你可以它们传递给:

funcname (IS_ON | IS_RED);   // passes in 0x05
Run Code Online (Sandbox Code Playgroud)

然后你用以下的东西提取它们:

void funcname (int bitmask) {
    if ((bitmask & IS_ON) == IS_ON) { // 0x05 & 0x01 -> 0x01
        // IS_ON bit is set.
    }
    :
}
Run Code Online (Sandbox Code Playgroud)

对于单位说明符,您可以使用if (bitmask & IS_ON)表单,但是如果您的说明符可能是多位值(例如,0到7的三位音量级别),则需要进行全面检查.