$a = 1;
$b = 2;
$c = 4;
$d = 8;
$e = 16;
$f = 32;
$g = 64;
.
.
.
上面的序列是n的2次幂,$ n是上面几个序列的数目,如果给你$ n,用一个算法找到$ n是由几个一起去它一个关于PHP十进制到二进制的算法
$a = 1;
$b = 2;
$c = 4;
$d = 8;
$e = 16;
$f = 32;
$g = 64;
.
.
.
上面的序列是n的2次幂,$ n是上面几个序列的数目,如果给你$ n,用一个算法找到$ n是由几个一起去它一个关于PHP十进制到二进制的算法
你可以得到单个位(为你变量$ a,$ b,...)与bitwise operators。
例如: 检查该位被设置
<?php
$n = 21; //number received from somewhere
if ($n & 1 == 1) {
echo "least significant bit is set";
}
if ($n & 2 == 2) {
echo "second least significant bit is set";
}
if ($n & 5 == 5) {
echo "third least and least significant bits are set";
}
if ($n & 3 == 1) {
echo "least significant bit is set and second least significant bit is unset";
}
?>
例2:按位加法和乘法
<?php
$n1 = 1 | 8 | 16; // 1 + 8 + 16 = 25
$n2 = 2 | 8; // 2 + 8 = 10
echo "$n1 and $n2\n"; // output: "25 and 10"
echo ($n1 | $n2) . "\n"; // bitwise addition 25 + 10, output: "27"
echo ($n1 & $n2) . "\n"; // bitwise multiplication 25 * 10, output: "8"
?>
示例3:这就是你需要
POW(2,$ I)在这种情况下产生编号为1,2,4,8,16,...,这些编号的二进制表示是:0000001,00000010,00000100,00001000,...,
按位与操作者进行零位,其中至少一个操作数具有零位,所以你可以很容易地位得到整数位
这是如何按位和作品:1101 & 0100 = 0100,1101 & 0010 = 0000
<?php
// get number from somewhere
$x = 27; // binary representation 00011011
// let's define maximum exponent of 2^$a (number of bits)
$a = 8; // 8 bit number, so it can be 0 - 255
$result = [];
$resIndex = 0;
for ($i = 0; $i <= $a; $i++) {
// here is the heart of algorithm - it has cancer, but it should work
// by that cancer I mean calling three times pow isn't effective and I see other possible optimalisation, but I let it on you
if ((pow(2, $i) & $x) > 0) {
echo pow(2, $i) . "\n"; // prints "1", "2", "8", "16"
$result[$resIndex] = pow(2, $i); // save it to array for later use
}
}
问题需要添加更多的细节,比如你想要达到什么目的?什么是预期的结果等... –
你想要这样的: - https://eval.in/751140 –
我把我的问题做了一些修改 – Zhmchen