1

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..

5
  • About your EDIT: you mean, passed as pointer? If it was passed as reference, then you wouldn't use the *. Commented Feb 1, 2013 at 11:47
  • 1
    This is such a classic bug that a minimum of research would give you the cause: bitwise & has lower operator precedence than ==. As a rule of thumb: if you don't know all of the operator precedence rules in detail, then use a parenthesis. Commented Feb 1, 2013 at 11:48
  • sorry for that, I already used a lot of parenthesis around (*q) because of not knowing the precedence, got confused because both the operands of & were 1 and still I was getting 0 as output... Commented Feb 1, 2013 at 11:51
  • @hyde, yes, passed as pointer...the function definition says void func(int *q,int*m) Commented Feb 1, 2013 at 11:52
  • Always use parentheses around bit operators. Their precedence is either not what you would naturally expect (&, ^, | are on the wrong side of comparison operators, probably because they were confounded with logical operators), or unclear (<<, >>). Commented Feb 2, 2013 at 9:02

1 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

Also (*q&1)==0 && q_1==1 would be just enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.