C# bitwise AND operator '&' logic

大城市里の小女人 提交于 2019-12-12 02:56:38

问题


I'm finding difficult to understand how the ´&´ operator works in relation to this code:

for(int cnt = 0; cnt < (1 << somelist.Count()); ++cnt)
{
    for (int i = 0; i < somelist.Count(); ++i)
    {
        //  1 << 0 -- 1 -> 1
        //  1 << 1 -- 10 -> 2
        //  1 << 2 -- 100 -> 4
        //  1 << 3 -- 1000 -> 8
        //  1 << 4 -- 10000 -> 16
        //  1 << 5 -- 100000 -> 32

        var l = (1 << i);
        if ((cnt & l) == 0)
        {
            // when is it getting here?
            // some code to execute
        }

    }
}

which ones are the cases when it enters the if condition and those where it doesn't? and why?

I already used the debugger on it, it is the logic behind that it's not clear. What it does is:

e.g.

var cnt = 0
var l = 1
if ((cnt & l)==0){ // true }

var cnt = 1
var l = 1
if ((cnt & l)==0){ // false }

var cnt = 1
var l = 2
if ((cnt & l)==0){ // true }

var cnt = 1
var l = 4
if ((cnt & l)==0){ // true }

var cnt = 3
var l = 2
if ((cnt & l)==0){ // false }

var cnt = 3
var l = 4
if ((cnt & l)==0){ // true }

回答1:


You need to understand how & bit wise and operator work.

Bitwise AND Operator: &

The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

To keep the things simple I took only one byte to explain.

First case

var cnt = 1
var l = 1
if ((cnt & l)==0){ // false }

00000001
00000001
===============
00000001

Comparing 00000001 which is 1 with zero will return false as 1 is not equal to zero.

Second Case

var cnt = 1
var l = 2
if ((cnt & l)==0){ // true }

00000001
00000010
===============
00000000

Comparing 00000000 which is 0 with zero will return true as 0 is equal to zero.



来源:https://stackoverflow.com/questions/36128918/c-sharp-bitwise-and-operator-logic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!