【发布时间】:2018-09-27 22:20:38
【问题描述】:
我试图弄清楚为什么在以下方法中,数组“8”中的最后一个值会满足“(8 & 7) == 0”的 where 子句。
public class Test {
public static void Main() {
int[] Arr = {-3, -1, 0, 1, 3, 8};
var s = from x in Arr where (x & (x-1)) == 0 select x+1;
foreach (int x in s)
Console.Write(x + " ");
}
}
它包含在招聘技能测试中,我一生都无法弄清楚为什么选择该值。无论哪种方式,我都不会在我的测试中使用它,但我很好奇,因为我以前从未遇到过。
【问题讨论】:
-
这是位运算符;它与布尔值无关。
-
8 & 1 == 0,它是按位的,==部分进行比较并返回一个布尔值。 -
研究你的位操作。 8 & 7 == 0。二进制中的 8 是 1000,而 7 是 0111。
And将它们加在一起就是 0000。 -
有人可以修改标题中的拼写吗?
标签: c# boolean bitwise-operators boolean-expression