Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precedence and bitmask operations

I've come across a (seemingly) very strange case.

Take the number 2 (0b10) and bitmask it with 1 (0b01)

This should produce 0b00 which is equivalent to 0.

However, here's where Mr Schrödinger comes in:

var_dump(0b10 & 0b01); // int(0) var_dump(0b10 & 0b01 == 0); // int(0) var_dump(0b10 & 0b01 != 0); // int(0) 

Whiskey. Tango. Foxtrot.

I am, admittedly, not the sharpest when it comes to bitwise operators - so maybe I've got horribly, horribly wrong somewhere?

However, in Python:

0b10 & 0b01 == 0 = True

0b10 & 0b01 != 0 = False

...so?

like image 278
Danny Kopping Avatar asked Feb 23 '14 22:02

Danny Kopping


People also ask

What is the precedence of operators?

The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3 , the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary.

What do you mean by precedence rule?

What Does Precedence Mean? Precedence, in C#, is the rule that specifies the order in which certain operations need to be performed in an expression. For a given expression containing more than two operators, it determines which operations should be calculated first.

What is meant by operator and operator precedence?

Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator.


1 Answers

You are actually doing this:

var_dump(0b10 & (0b01 == 0)); var_dump(0b10 & (0b01 != 0)); 

Try:

var_dump((0b10 & 0b01) == 0); var_dump((0b10 & 0b01) != 0); 
like image 56
Matthew Avatar answered Oct 27 '22 23:10

Matthew