How to check whether the N bit of a number is set or not in PHP

2 Answers

0 votes
function is_N_bit_set($num, $N) { 
    if ($num & (1 << ($N - 1))) {
        echo "Bit set <br />"; 
    }
    else {
        echo "Bit not set <br />"; 
    }
} 
  
$num = 12; 

echo str_pad(decbin($num), 3, '0', STR_PAD_LEFT) . "<br />";

$N = 3; 
is_N_bit_set($num, $N);

$N = 4;
is_N_bit_set($num, $N);

$N = 1;
is_N_bit_set($num, $N);




  
/*
run:

1100
Bit set
Bit set
Bit not set 
  
*/




  
/*
run:

1100
Bit set
Bit set
Bit not set 
  
*/

 



answered Aug 22, 2019 by avibootz
0 votes
function n_bit_set($num, $N) { 
    return $num & (1 << ($N - 1));
} 
  
$num = 12; 

echo str_pad(decbin($num), 3, '0', STR_PAD_LEFT) . "<br />";

$N = 3; 
if (n_bit_set($num, $N)) {
    echo "Bit set <br />"; 
}
else {
    echo "Bit not set <br />"; 
}


$N = 1; 
if (n_bit_set($num, $N)) {
    echo "Bit set <br />"; 
}
else {
    echo "Bit not set <br />"; 
}




  
/*
run:

1100
Bit set
Bit not set 
  
*/

 



answered Aug 23, 2019 by avibootz
...