C++ bitwise operations

天大地大妈咪最大 提交于 2019-12-24 08:49:26

问题


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

In some intermediate step, I have the bit representations as

q = 11000000000000000000000000000000
q_1 = 00000000000000000000000000000001

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.

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?

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


回答1:


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.

So:

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

should be:

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

See: http://en.cppreference.com/w/cpp/language/operator_precedence



来源:https://stackoverflow.com/questions/14645473/c-bitwise-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!