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

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.