Precedence and bitmask operations

PhpBit ManipulationBitwise OperatorsOperator Precedence

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanny KoppingView Question on Stackoverflow
Solution 1 - PhpMatthewView Answer on Stackoverflow