c# - C# 如何评估数组循环 boolean 相等性?

标签 c# boolean bitwise-operators boolean-expression

我试图找出为什么在以下方法中数组“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 + " ");
      } 
}

它包含在招聘技能测试中,我一生都无法弄清楚为什么选择该值。不管怎样,我不会在测试中使用它,但我很好奇,因为我以前从未遇到过这个。

最佳答案

因此单个 & 是一个按位运算符。它正在查看这些数字的二进制表示形式。

7 = 0111 和 8 = 1000

当你将它们组合起来时,你会得到 0。

这就是为什么你的方法打印出 9。

关于c# - C# 如何评估数组循环 boolean 相等性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49886751/

相关文章:

c# - appdata的这种方法也适用于linux吗?

c++ - 将 reinterpret_cast 与 bool 一起使用

c# - 当 x 和 y 都为真时, "x & y"怎么可能为假呢?

assembly - 浮点按位运算的用处

c# - 可移植类库中的 MvvmLight - 如何进行单元测试

c# - C# 中的 PHP var_dump 转储数组或对象?

c# - 从 AWS S3 读取流涉及加载整个文件

java - 使用 getClass() 获取类时编译错误

boolean - XOR和NOT-EQUAL-TO有什么区别?

64 位整数中的 C++ 位