与整数的布尔运算
这可能是非常基本的......但我似乎不明白:
如何
(2 & 1) = 0
(3 & 1) = 1
(4 & 1) = 0
等等......
上面的这种模式似乎有助于找到偶数,
或者
(0 | 1) = 1
(1 | 1) = 1
(2 | 1) = 3
(3 | 1) = 4
(4 | 1) = 5
(5 | 1) = 5
我知道布尔代数如何在位之间工作。 但我不明白布尔代数如何与整数一起工作(至少在 C# 中)。
提前致谢。
This is probably pretty basic... but I don't seem to get it:
How does
(2 & 1) = 0
(3 & 1) = 1
(4 & 1) = 0
etc..
This pattern above seems to help find even numbers
or
(0 | 1) = 1
(1 | 1) = 1
(2 | 1) = 3
(3 | 1) = 4
(4 | 1) = 5
(5 | 1) = 5
I know how boolean algebra works between bits. But I don't understand how Boolean algebra works with integers (in C# at the least).
thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您得到第一个结果是因为您正在两个数字的位字符串之间执行布尔
and
:实际上,您正在测试是否设置了“1”位,这仅适用于奇数。
执行
or
操作时:由于在这种情况下
or
的效果是始终设置1
位,因此偶数将增加1到最接近的较大奇数。You are getting the first result because you are performing a boolean
and
between the bit strings of the two numbers:In effect, you are testing whether the '1' bit is set, which will only be true for odd numbers.
When performing
or
operations:Since in this case the effect or the
or
is to always set the1
bit, even numbers will be incremented by one to their nearest greater odd number.它在 C# 中的工作方式与在二进制中的工作方式相同。
<代码>2 | 1 = 3 和
4 | 1 = 5。
要理解这一点,您需要考虑 1、2、3、4 和 5 的二进制表示形式:
010 | 001 = 011 和 100 | 001 = 101。
同样:
010 & 001 = 000
和011 & 001 = 001
It works the same way in C# as it does in binary.
2 | 1 = 3
and4 | 1 = 5
.To understand this, you need to think about the binary representation of 1,2,3,4,and 5:
010 | 001 = 011
and100 | 001 = 101
.Similarly:
010 & 001 = 000
and011 & 001 = 001
关键是 CPU 正在并行执行 32 个布尔运算,每个布尔运算对应输入整数的每个位位置(当然假设是 32 位整数)。
The key is that the CPU is doing 32 boolean operations in parallel, one for each bit position of the input integers (assuming 32 bit integers, of course).
它对整数进行按位运算。 它正在对第一个整数中的每个位与另一个整数中的相应位进行逻辑或/与。 然后它返回所有这些操作的结果。 例如,4 = 0100 和 1 = 0001,这些逻辑与将按顺序对位进行位运算并得到 0000(因为 0&0 = 0、1&0 = 0、0&0 = 0 和 0&1 = 0)。 对于 or,您将得到 0101(因为 0|0 = 0、1|0 = 1、0|0 = 0 和 0|1 = 1)。 诀窍在于,这些是按位运算,而不是仅对 C# 中的布尔值进行运算的逻辑运算。
It is doing bitwise operations on the integer. That it is doing a logical or/and of each bit in the first integer with the corresponding bit in the other integer. It then returns the result of all of these operations. For example, 4 = 0100 and 1 = 0001, a logical and of these would and bit the bits in order and get 0000 (since 0&0 = 0, 1&0 = 0, 0&0 = 0, and 0&1 = 0). For or, you would get 0101 (since 0|0 = 0, 1|0 = 1, 0|0 = 0, and 0|1 = 1). The trick is that these are bitwise operations, not logical operations which operate only on boolean values in C#.