条件语句如何与按位运算符一起使用? [英] How does condition statement work with bit-wise operators?

查看:76
本文介绍了条件语句如何与按位运算符一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解条件如何与按位运算符一起使用.可以通过以下方法检查数字是偶数还是奇数:

I tried to understand how if condition work with bitwise operators. A way to check if a number is even or odd can be done by:

#include <iostream>
#include <string>
using namespace std;

string test()
{
    int i = 8;  //a number
    if(i & 1)
      return "odd";

    else
      return "even";       
}

int main ()
{
  cout << test();
  return 0;
}

我不了解的部分是if条件如何工作.在这种情况下,如果i = 8,则在if语句中执行 1000&1 ,应返回1000,等于8.

The Part I don't understand is how the if condition work. In this case if i = 8 then the in If statement it is doing 1000 & 1 which should gives back 1000 which equal 8.

如果i = 7,则在if语句中应该执行 111&1 会返回111,等于7

If i = 7, then in if statement it should be doing 111 & 1 which gives back 111 which equal 7

为什么if(8)返回偶数"而if(7)返回奇数"呢?我想我想了解在处理按位运算符时,if语句检查的是True,什么是False.

Why is it the case that if(8) will return "even" and if(7) return "odd"? I guess I want to understand what the if statement is checking to be True and what to be False when dealing with bit-wise operators.

当我写下这个问题时,只是因为它实际上在做

Just A thought when I wrote this question down is it because it's actually doing

for 8: 1000 & 0001 which gives 0
for 7: 0111 & 0001 which gives 1?

推荐答案

是的,您就在最后一部分.二进制& | 一点一点地执行.自

Yes, you are right in the last part. Binary & and | are performed bit by bit. Since

1 & 1 == 1
1 & 0 == 0
0 & 1 == 0
0 & 0 == 0

我们可以看到:

8 & 1 == 1000 & 0001 == 0000

7 & 1 == 0111 & 0001 == 0001

您的 test 函数可以正确计算数字是偶数还是奇数,因为 a&1 测试1处是否有 1 ,仅对奇数存在.

Your test function does correctly compute whether a number is even or odd though, because a & 1 tests whether there is a 1 in the 1s place, which there only is for odd numbers.

这篇关于条件语句如何与按位运算符一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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