我有旗帜
int A = 1;
int B = 2;
int C = 4;
Run Code Online (Sandbox Code Playgroud)
我想做一个检查,只能为一个函数指定一个标志
check(A | B | C) ; // invalid
check(A); // valid
check(B); // valid
check(B | C); // invalid
void check(int flags) {
// check that if A is specified, then B and C can't
// check that if B is specified, then A and C can't
// check that if C is specified, then B and A can't
}
Run Code Online (Sandbox Code Playgroud)
如果没有大量的"if"陈述,我怎样才能做到这一点?
要将位设置为位置n,您需要设置值2 ^ n.
因此,如果要检查是否只指定了其中一个标志,那么您只想询问该数字是否为2的幂.
以下是关于如何执行此操作的问题:如何检查数字是否为2的幂
正如格雷厄姆所说,你可以读到这个问题,说必须设置一个比特(即它不能为零).所以要做到这一点,另外,检查它是否为非零并且它小于或等于C.