此C ++代码中`&`运算符的含义 [英] The significance of `&` operator in this C++ code

查看:70
本文介绍了此C ++代码中`&`运算符的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一些这样的代码:

I saw some code like this:

void testCase2 (int variant)
{    
  if (variant & 0x1)
  {
    return;
  }
}

& 运算符在if语句中是什么意思,它是 == 吗?为什么要使用& ?

What does the & operator mean in the if statement, is it ==? Why to use &?

推荐答案

& 是按位AND运算符.给定两个整数操作数,它将在每个位位置上执行与"运算,即结果将仅设置在两个操作数中设置的那些位.

& is the bitwise AND operator. Given two integer operands, it does an AND operation on each bit position, i.e. in the result only those bits will be set that were set in both operands.

如果在这种情况下其中一个操作数是 0x1 ,则当且仅当该位也是 时,结果也将是 0x1 >在 other 操作数(此处为 variant )中设置.

If one of the operands is 0x1 as in this case, the result will be 0x1 if, and only if, that bit is also set in the other operand (here, variant).

由于C/C ++认为任何非零整数为 true

As C/C++ considers any non-zero integer to be true,

if (variant & 0x1)

检查是否设置了 variant 中的最低有效位.

checks if the least-significant bit in variant is set.

类似地,

if (variant & 0x2)

将检查是否设置了 variant 中的第二个最低有效位,并且

would check if the second least-significant bit in variant is set, and

if (variant & 0x3)

将检查是否设置了 variant 中两个最低有效位的 .

would check if either of the two least-significant bits in variant is set.

这篇关于此C ++代码中`&`运算符的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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