Search code examples
phpmathlogarithm

How to express an integer as the sum of powers-of-two?


I have this number:

0101

and I know it is the binary sum of

0100
0001

How can I get those values from the first one?

EDIT

I have create a snippet of code based on the logic by JoeCortopassi. The snippet its this:

protected function _getSitesPublished($value) {
    static $bits = null;
    if (!$bits) {
        $bits = array ();
        $bit = 0;
        $x = 0;
        while ($bit < 4294967295) {
            $bit = pow (2, $x);
            $bits [$bit] = $bit;
                            ++ $x;
        }
    }
    $sites = array ();
    foreach ($bits as $bit) {
        if (($value & $bit) == $bit) {
            $sites [] = $bit;
        }
    }
    return $sites;
}

It only create the bits the first time the method its called. I have to make the comprobation

if (($value & $bit) == $bit)

since $value & $bit will return an int (may be other than 0, as in 6 & 3) and because of that I can't use only if ($value & $bit)

Thanks to all for your help.

EDIT 2 Oops! I had a little bug... forgot to increase the $x XD


Solution

  • Using JoeCortopassi's code:

    $value= bindec($binary);
    $sums=array();
    $counter=1;
    while($counter<=$value){
        if($counter & value)
            $sums[]=$counter;
        $counter*=2;
    }
    print_r($sums);