3

我有下一个代码:

int main()
{
 OwnSelect(23, FD_READ | FD_WRITE); // <---- Several arguments as one
 return 0;
}

int OwnSelect(SOCKET s, long lNetworkEvents)
{
 // How can i check that FD_READ has been passed?
 if(lNetworkEvents == FD_READ)
 {
  // never here
 }
 return 0;
}

无论是否已通过 FD_READ 传递了另一个 FD,我如何检查是否已通过 FD_READ。谢谢!

4

4 回答 4

8

似乎您在这里错过了一些基本的位操作。您正在 OR'ing FD_READ 和 FD_WRITE(| = 按位或),从而将两个值指示的位设置为参数。要检查 FD_READ 是否通过,您需要将 lNetworkEvents 与 FD_READ 进行 AND 并检查结果是否等于 FD_READ,如下所示:

if (FD_READ == (lNetworkEvents & FD_READ)) { ... }

这当然假设 FD_READ 和 FD_WRITE 是打算以这种方式使用的值(即通常没有重叠位)。

编辑:固定,wabepper 是绝对正确的 :) 哎呀!

于 2012-06-29T10:12:20.260 回答
2

通过使用&

if ((lNetworkEvents & FD_READ) == FD_READ) {
    ...
}
于 2012-06-29T10:14:31.813 回答
2
if ( (iNetworkEvents & FD_READ) != 0 )

is what you're looking for here. This works well as long as the "argument" in question is a single bit (a boolean). For more complex operations, like those on the floatfield in fmtflags, you'll need to compare with the correct value:

switch (myFlags & std::ios_base::floatfiled )
{
case std::ios:base::fixed:
    //  ...

//  ...
}

Finally if the field is an integral value (e.g. 0...7 on 3 bits), you'll have to both mask and shift to get the correct value. (If the value is signed, it's even more complex.)

于 2012-06-29T10:16:38.457 回答
1

http://www.cplusplus.com/doc/boolean/ - that might help you

a very simplistic explanation: imagine

FD_READ = 0b01
FD_WRITE = 0b10

then passing FD_READ | FD_WRITE will give you 0b11 as argument

to check if FD_READ is there basically is to check if that last bit is 1, doable by:

x & 0b01 // aka
x & FD_READ
于 2012-06-29T10:15:38.563 回答