更新时间:2023-11-24 22:23:46
按位运算符 &
比较每一对位。仅当左右操作数至少有一个匹配位设置为1时,结果才为非空。
The bitwise operator &
compares each individual pair of bits. The result will be non-null only if the left and right operands have at least one matching bit set to 1.
示例:0100 AND 0010→0000但0110 AND 0010 →0010。
Example : 0100 AND 0010 → 0000 but 0110 AND 0010 → 0010.
此运算符允许您使用单个整数值在不同位上存储多个布尔值,然后使用第二个值(称为掩码)来过滤比特。
This operator allows you to use a single integer value to store several booleans on different bits, then use a second value (known as a mask) to filter the bits.
kSCNetworkFlagsReachable
等于 1<< 1
( 2
)。因此, flag&仅当
才为真。 flag
的第二个最低有效位设置为1时,kSCNetworkFlagsReachable
kSCNetworkFlagsReachable
is equal to 1<<1
(2
). Thus, flag & kSCNetworkFlagsReachable
is true only if the second least significant bit of flag
is set to 1.
使用&&
代替&
是一个常见的错误。编译器将尝试检测该错误。在您的示例中, kSCNetworkFlagsReachable
是一个常量值。由于 kSCNetworkFlagsReachable
是常量且始终为真,因此测试 flag&& kSCNetworkFlagsReachable
为true与测试 flag
是否为真相同。因此,您不太可能真的想在逻辑运算中使用常量值。这就是编译器发出警告的原因。
Using &&
instead of &
is a common mistake. The compiler will try to detect that mistake. In your example, kSCNetworkFlagsReachable
is a constant value. As kSCNetworkFlagsReachable
is constant and always true, testing whether flag && kSCNetworkFlagsReachable
is true is the same as testing whether flag
is true. Thus it is very unlikely that you really wanted to use a constant value in a logical operation. That's why the compiler emits the warning.