PHP Bitmask says true when it should be false

I compare two variables with bitwise AND, and it should not return true, but this happens. Here is my code

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

where $dequal to 15, and $wequal to 31.

Why does it return true when bitmasks are different?

+4
source share
2 answers

You do not compare two variables, you and instead . With bitwise And you can not compare anything.

($ d and $ w) means $ d AND $ w, where AND is the logical AND operator. Here you specify two integer variables that will also give an integer. And the integer is interpreted as TRUE in comparison if it is not null.

$d 01111
$ w - 11111
($ d $w), , 01111. var_dump ($ d $w), , , ;

, ANDed, , :

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

: ANDed $d $w $d.

<?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 />';
}

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

15 31 0, , . , :

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

.

0

All Articles