Operator precedence, was: Bitwise operator not working as expected

Hi All,

For some reason, when I'm using bit-wise operators I do not get the behaviour that I would expect...

Index = 1;
j1 = Index & 1 == 1; // Would Expect j1 to equal 1 and the watch window states j1 is 1
j2 = Index & 2 == 2; // Would Expect j2 to equal 0 but the watch window states j2 is 1
j3 = Index & 4 == 4; // Would Expect j3 to equal 0 but the watch window states j3 is 1

Can some please shed some light on where I'm going wrong?

Thanks!

@SippDealer

try this:

Index = 1;
j1 = (Index & 1) == 1; 
j2 = (Index & 2) == 2; 
j3 = (Index & 4) == 4; 

Operators precedence rules....

Your code is equivalent to:

Index = 1;
j1 = Index & (1 == 1); 
j2 = Index & (2 == 2);
j3 = Index & (4 == 4);

Review the "Operator precedence and the parentheses" section here

3 Likes

Thanks for that!

It now works great thank you.