0

我需要使用两个函数,一个是对复选框的值求和,然后将该值放入一个 cookie 中,用于网站上用于搜索页面的众多复选框之一。

第二个函数检查该位是否已设置,我不知道该函数应该做什么。我知道它应该做什么,但我没有看到它实际上在函数中做任何事情。

所有的值都是 2 的幂,并且应该查看总和是否包含 2 的幂。下面是函数:

function isBitSet($power, $decimal)
{

    if((pow(2,$power)) & ($decimal))
    {       
            return 1;
    }
    else
            return 0;

}
4

1 回答 1

0

& is the bitwise AND operator (not to be confused with &&, which is a comparison operator)! & compares the thing on its left and the thing on its right, bit by bit, and only outputs a 1 for each bit where BOTH inputs bits had a 1. I'll show an example:

In the following example, the top number is pow(2, $power), where $power = 3. It's written in binary form to make it clearer: doing 2 to the power of 3 has shifted a binary 1 right 3 places.

  00001000   <- this is pow(2, 3)
& 01101010   <- this is your $decimal (in binary form)
  ========
= 00001000

You see? All the output bits are 0, except where BOTH input bits were 1.

What we have done is we have used pow(2, 3) as a MASK: it has cleared EVERY bit to 0, except the one we are interested in (bit 3). That bit will be 1 if $decimal contains this particular power of 2, otherwise it will be 0:

$decimal contains that power of 2 -> result will be 00001000
$decimal does not contain that ^2 -> result will be 00000000

Since any non-zero integer evaluates to true in PHP, the if will occur if that bit is set (i.e. $decimal contains that power of 2), and the else will occur if that bit is not set (because the & will result in an output of 00000000).

Please comment if you need any of that clarified. Hope it helps.

于 2013-11-12T01:02:58.187 回答