Jes*_*nds 5 c c++ parameters bit-manipulation function
好吧,这可能听起来有点含糊不清,但那是因为我不知道如何用不同的方式来表达它.我将尝试解释我的意思:通常在某些库中,'init'函数接受一些参数,但该参数接受多个参数(右..).一个例子,就像这样:
apiHeader.h
#define API_FULLSCREEN 0x10003003
#define API_NO_DELAY 0x10003004
#define API_BLAH_BLAH 0x10003005
Run Code Online (Sandbox Code Playgroud)
main.c中:
apiInit(0, 10, 10, 2, API_FULLSCREEN | API_NO_DELAY | API_BLAH_BLAH);
Run Code Online (Sandbox Code Playgroud)
这是如何运作的?我无法在任何地方找到答案,很可能因为我不知道它是如何实际调用的,所以我不知道要搜索什么.这在我目前的项目中非常有用.
提前致谢!
该参数通常称为"$ FOO flags",值为or-ed.关键是参数是一个数值类型,它被构造为or多个可能值的按位.
在处理函数中,通常使用按位测试值and:
if ( (flags & API_FULLSCREEN) != 0 )
Run Code Online (Sandbox Code Playgroud)
您必须小心以保持OR运算线性的方式分配值.换句话说,不要or像在标题中那样在两个不同的值中设置相同的位.例如,
#define API_FULLSCREEN 0x1
#define API_NO_DELAY 0x2
#define API_BLAH_BLAH 0x4
Run Code Online (Sandbox Code Playgroud)
工作并允许您解析函数中的所有标志组合,但是
#define API_FULLSCREEN 0x1
#define API_NO_DELAY 0x2
#define API_BLAH_BLAH 0x3
Run Code Online (Sandbox Code Playgroud)
不是因为API_FULLSCREEN | API_NO_DELAY == API_BLAH_BLAH.
从更高级别查看,flags int是一个穷人的变量参数列表.如果你考虑使用C++,你应该将这些细节封装在一个类或至少一个类中std::bitset.
第五个参数通常是一个掩码.它的工作原理是定义几个consts(可能是一个enum),其值为2的幂或它们的组合.然后使用它们将它们编码为单个值|,并使用解码&.例:
#define COLOUR_RED 0x01
#define COLOUR_GREEN 0x02
#define COLOUR_BLUE 0x04
#define COLOUR_CYAN (COLOUR_BLUE | COLOUR_GREEN) // 0x06
// Encoding
SetColour(COLOUR_RED | COLOUR_BLUE); // Parameter is 0x05
// Decoding
void SetColour(int colour)
{
if (colour & COLOUR_RED) // If the mask contains COLOUR_RED
// Do whatever
if (colour & COLOUR_BLUE) // If the mask contains COLOUR_BLUE
// Do whatever
// ..
}
Run Code Online (Sandbox Code Playgroud)