C#按位与运算符'&'逻辑 [英] C# bitwise AND operator '&' logic

查看:226
本文介绍了C#按位与运算符'&'逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现难以理解&"运算符相对于此代码的工作方式:

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
        }

    }
}

进入if条件时有哪些情况,没有进入if条件时有什么情况?为什么?

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 }

推荐答案

您需要了解&明智和操作员的工作.

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

按位与运算符:&

按位AND运算符(&)将第一个操作数的每个位与 第二个操作数的相应位.如果两个位均为1,则 相应的结果位设置为1.否则,相应的 结果位设置为0.

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.

第一种情况

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

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

将00000001与1比较为零将返回false,因为1不等于零.

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

第二种情况

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

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

将00000000与0进行比较,则零将返回true,因为0等于零.

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

这篇关于C#按位与运算符'&amp;'逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆