C ++位运算 [英] C++ bitwise operations

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

问题描述

我在操作两个整数的各个位,(我用G ++为Ubuntu机器上编译)。

I am operating on individual bits of two integers, (i am using g++ for compilation on Ubuntu machine).

在一些中间步骤,我有位再presentations为

In some intermediate step, I have the bit representations as

q = 11000000000000000000000000000000
q_1 = 00000000000000000000000000000001

现在我要检查q和Q_1单位的地方是否都相同与否。所以,我检查(* Q)及1 == Q_1 中的if条件,其做工精细

Now I want to check whether unit's places of q and q_1 are both same or not. so, I am checking (*q)&1==q_1 in the if condition, and its working fine.

但是,每当我要检查该单位的地方问是0和Q_1是1,我想我应该做的((* Q)及1 == 0)及和放大器; (Q_1 == 1),但它不工作了预期。为了调试,我 COUT ED的值((* Q)及1 == 0)(Q_1 == 1)单独和他们得到了打印为 1 。但是,值((* Q)及1 == 0)及和放大器; (Q_1 == 1)印刷得到了为0。为什么?

But whenever I want to check that unit's place of q is 0 and that of q_1 is 1, I thought I should do ((*q)&1==0) && (q_1==1), but it is not working out as expected. For debugging, I cout ed the values of ((*q)&1==0) and (q_1==1) individually and they got printed as 1. However, the value of ((*q)&1==0) && (q_1==1) got printed as 0. Why?

*的编辑:* 的在功能方面,Q是通过引用传递,所以我使用* Q来获取值。

*EDIT : * In the function, q was passed by reference, so I am using *q to get the value..

推荐答案

在C和C ++中,按位&安培; 运营商实际上具有较低的precedence比等价运营商 == 。你需要换你位运算符在括号中。

In C and C++, the bitwise & operator actually has lower precedence than the equivalence operator ==. You'll need to wrap your bitwise operators in parentheses.

所以:

((*q)&1==0) && (q_1==1)

应该是:

(((*q)&1)==0) && (q_1==1)

请参阅:<一href=\"http://en.cp$p$pference.com/w/cpp/language/operator_$p$pcedence\">http://en.cp$p$pference.com/w/cpp/language/operator_$p$pcedence

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

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