Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/245.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP十进制到二进制的一种算法_Php - Fatal编程技术网

PHP十进制到二进制的一种算法

PHP十进制到二进制的一种算法,php,Php,上面的序列是n到2的幂,$n是上面几个序列的个数,如果给你$n,使用一个算法来找到$n,通过这个算法,几个序列一起在它上面你可以得到单个位(对于你的变量$a,$b,…) 例如: 检查设置了哪些位 $a = 1; $b = 2; $c = 4; $d = 8; $e = 16; $f = 32; $g = 64; . . . 例2:按位加法和乘法 <?php $n = 21; //number received from somewhere if ($n &

上面的序列是n到2的幂,$n是上面几个序列的个数,如果给你$n,使用一个算法来找到$n,通过这个算法,几个序列一起在它上面

你可以得到单个位(对于你的变量$a,$b,…)

例如: 检查设置了哪些位

$a = 1;
$b = 2;
$c = 4;
$d = 8;
$e = 16;
$f = 32;
$g = 64;
   .
   .
   .

例2:按位加法和乘法

<?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";
}
?>

这就是你需要的

pow(2,$i)在这种情况下产生数字1,2,4,8,16,…,这些数字的二进制表示为:0000001,00000010,00000100,000010000

按位and运算符生成零位,其中至少有一个操作数具有零位,因此您可以轻松地逐位获得整数

这就是按位and的工作方式:1101&0100=0100,1101&0010=0000

<?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"
?>

问题需要添加更多细节,比如您到底想要实现什么?预期结果是什么等…你想要这样:-我把我的问题做了一些修改,还是做了家庭作业?当然不是…我需要的是数字,输入任何超过2N的加法数字,可以输出数字我不能控制自己,我仍然认为你需要位运算。。。检查我添加的第二个例子,如果它是你想要的。我需要这个。第二个例子,如果我给你$n2($n2=2+8),我怎么能得到2和8呢?这是第一个例子,但现在我明白了。我将尝试创建第三个示例,向您展示如何根据您的需要使用它。我在沙盒中测试了第三个示例,它的工作原理与您在上一篇评论中所描述的一样
<?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
    }
}