Artemis
Artemis

Reputation: 51

PHP Bitmask says true when it should be false

I am comparing two variables with a bitwise AND, and it shouldn't return true but it does. Here is my code,

if($d & $w){
    return true;
} else {
    return false;
}

where $d is 15 and $w is 31.

Why does it return true when the bitmasks are different?

Upvotes: 4

Views: 122

Answers (2)

hherger
hherger

Reputation: 1680

You are not comparing the two variables, you are anding them instead. Whith a bitwise AND you cannot compare anything.

($d & $w) means $d AND $w, where AND is the boolean AND operator. You are anding two integer variables here which will give an integer too. And an integer is interpreted as TRUE in a comparison if it is not null.

$d is binary 01111
$w is binary 11111
($d & $w) obviously is binary 01111. If you do a var_dump($d & $w) you see that the result is an integer, not a boolean;

So, if you mean to compare the ANDed value, you should choose a comparison construct, like this:

if ( ($d & $w) == $d ) ...

which means: if the ANDed value of $d and $w equals $d.

Code example

<?php

$d = 15;
$w = 31;
$res = ($d & $w);
echo '$d=' . decbin($d) . '<br />';
echo '$w=' . decbin($w) . '<br />';
echo '($d & $w)=' . decbin($res) . '<br />';

// Boolean AND only
if($d & $w){
    echo '($d & $w) is true' . '<br />';
} else {
    echo '($d & $w) is false' . '<br />';
}

// Comparison with boolean AND
if ( ($d & $w) == $d ) {
    echo '(($d & $w) == $d) is true' . '<br />';
} else {
    echo '(($d & $w) == $d) is false' . '<br />';
}

// Simple comparison
if ($d == $w) {
    echo '($d == $w) is true' . '<br />';
} else {
    echo '($d == $w) is false' . '<br />';
}

Result

$d=1111
$w=11111
($d & $w)=1111
($d & $w) is true
(($d & $w) == $d) is true
($d == $w) is false

Upvotes: 2

Munsterlander
Munsterlander

Reputation: 1386

Because 15 and 31 are greater than 0 which is false, so the bits in the set rate as true. What I think you are wanting is:

if(($d & $w)== true){
    return true;
} else {
    return false;
}

You need to use parentheses to ensure the desired precedence.

Upvotes: 0

Related Questions