0

I have two decimal numbers. If both the bits at any identical positions are set, then comparison should return true otherwise false. For example

  1. number1 = 196 = 11000100
  2. number2 = 4 = 00000100
  3. number3 = 16 = 00010000

=> Comparison of number1 and number2 will return true.

=> Comparison of number1 and number3 will return false.

=> Comparison of number2 and number3 will return false.

In PHP, is there any inbuilt function for this type of comparison or how can we write custom logic for it?

Dinesh Belkare
  • 639
  • 8
  • 24

3 Answers3

3

From Bitwise Operators:

$a & $b And Bits that are set in both $a and $b are set.

var_dump(196 & 4);
var_dump(196 & 16);
var_dump(4 & 16);

Where 0 is false non-zero is true:

int(4)
int(0)
int(0)

You can cast to boolean true or false:

var_dump((bool) (196 & 4));
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

Use bitwise operators:

$number1 = 196;
$number2 = 4;

if ($number1 & $number2){
  echo "Number 1 and 2 are equal";
} else {
  echo "Number 1 and 2 are not equal";
}
mrzo
  • 2,002
  • 1
  • 14
  • 26
0

The bitwise answer is way better than mine, but here's how to do it without using bitwise operators:

<?php


function hasMatchingBits($x, $y) 
{
    $x = strrev(decbin($x));
    $y = strrev(decbin($y));
    $lengthX = strlen($x);
    $lengthY = strlen($y);
    $length = $lengthX < $lengthY ? $lengthX : $lengthY;

    for ($i = 0; $i < $length; $i++) {
        if ($x[$i] === '1' && $y[$i] === '1') {
            return true;
        }
    }

    return false;
}

echo hasMatchingBits(196, 4) ? "Yes\n" : "No\n";
echo hasMatchingBits(196, 16) ? "Yes\n" : "No\n";
echo hasMatchingBits(4, 16) ? "Yes\n" : "No\n";

Which you can see here https://3v4l.org/8lSJX

delboy1978uk
  • 12,118
  • 2
  • 21
  • 39