关于PHP十进制到二进制

时间:2017-03-09 06:46:01

标签: php

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

上面的序列是n的幂2,$ n是上面几个串联的数字,如果给你$ n,使用算法找到$ n是由几个一起得到的它

1 个答案:

答案 0 :(得分:0)

您可以使用bitwise operators获得单个位(对于变量$ a,$ b,...)。

实施例: 检查设置了哪些位

<?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&amp; 0100 = 0100,1101&amp; 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
    }
}
相关问题