Jump to content

Bit Testing and Setting, What am I doing wrong?


awatson

Recommended Posts

I'm working on my first PHP script, and I need to be able test the bits in a variable as well as set or reset them when needed.  I've tracked down a few bit flag examples, but none of them worked for me, so I've tried to tackle it on my own.

 

I wrote this "simple" function to get the state of a bit:

 

 function get_bit($value, $bit) {
   $mask=1 << $bit;
   $x=($value & $mask);
   if ($x==0) { 
    $result=0; 
   } else { 
    $result=1; 
   }
   echo bin2hex($value)." ".$mask." ".$x."<br />";
   return $result;
   } 

 

$value is the incoming value (between 0 and 255)

 

$bit is the number of the bit (0-7)

 

The echo line is just for my testing, but it "should" show the hex value of the variable, the appropriate mask corresponding to the bit (1,2,4,8,16,32,etc.), and a variable ($x) that is either zero or matches the calculated mask.

 

Unfortunately, while the hex value and mask appear to be calculated correctly, the $x variable is always coming out as zero. I'm a PHP newbie. What am I doing wrong?

 

Ideally, the function should return either 0 or 1 depending on whether the selected bit is set or cleared.

 

I also tried a simple shift approach like $result=($value >> $bit) & 1, but that didn't work either. I'm obviously overlooking something.

 

Thanks,

 

Anthony

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.