使用按位和运算符c ++ [英] using bitwise and operator c++

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

问题描述

我有以下代码

int n = 50;
while(n) {                         //1
    if(n & 1) cout << "1" << endl; //2 
    //right shift the number so n will become 0 eventually and the loop will terminate
    n >>= 1;                       //3
}

当我们对数字使用按位和1(& 1)时,我们将获得相同的数字.现在我的问题是c ++如何评估以下表达式:n&1.由于:

When we use bitwise and 1 (& 1) with a number we get back the same number. Now my question is how does c++ evaluates the following expression: n & 1. Since:

  n = 50
  In binary form 50 is:            110010
  If we bitwise 1 then we get:  AND     1 = 110010
  Now in c++ (2) the expression evaluates like this:
  Instead of getting the whole sequence of bits (110010) bitwise anded with 1    
  it evaluates only the number of right bits we bitwise. In my example:
  n=50, 110010, use n & 1 ==> 0 AND 1 instead of 110010 AND 1.

c ++是否有理由按位处理这样的事情?我的猜测是与编译器有关吗?

Is there a reason that c++ treats the bitwise and like this? My guess would be it has to do with the compiler ?

推荐答案

来自维基百科:

按位AND运算符是单个&符:&.它只是AND的表示形式,它对操作数的位而不是操作数的真值进行工作.按位二进制AND以二进制形式对数字的每个位置的位进行逻辑与(如上表所示).

The bitwise AND operator is a single ampersand: &. It is just a representation of AND which does its work on the bits of the operands rather than the truth value of the operands. Bitwise binary AND does the logical AND (as shown in the table above) of the bits in each position of a number in its binary form.

在您的示例中, 110010 &将 1 1 视为 000001 ,然后对每个位进行 anded ,即可得到结果.实际上,我使用以下方法: 1& number 检查偶数和奇数.这是这样的:

In your example 110010 & 1, 1 is considered as 000001, and then each bit is anded and you get the result. In fact, I use this method: 1&number to check for even and odd numbers. This is how:

if(1 & num)
  printf("it is odd");
else 
  printf("it is even");

它是这样工作的:假设您有一个8位数字.现在, 1 的8位符号将为 00000001 .

This is how it works: suppose you have an 8 bit number. Now, the 8 bit notation of 1 will be 00000001.

如果我现在在每个位上执行,则对于所有前七个位,我将获得 0 ,因为它将是 0&什么将为0.现在, 1 的最后一位为1.因此,如果我的数字的最后一位也为 1 ,那么 1&1 = 1 ,如果我的最后一位是 0 ,则 1&0 = 0 .

If I now perform and on each bit, for all the first seven bits I will get 0, because it will be 0 & anything will be 0. Now, the last bit of 1 is 1. So, if my number also has last bit as 1, then 1 & 1 = 1, and if my last bit is 0, then 1 & 0 = 0.

我的号码的最后一位何时是 1 ?而什么时候 0 ?转换为十进制格式时,最后一位乘以2 0 .并且,2 0 =1.如果此 1 乘以1,我们得到一个奇数,如果它乘以0,我们得到一个偶数.

When will the last bit in my number be 1? And when 0? When converting to decimal form, the last bit is multiplied by 20. And, 20 = 1. If this 1 is multiplied with 1, we get an odd number, and if it is multiplied with 0, we get an even number.

这篇关于使用按位和运算符c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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