LoginSignup
8
7

More than 5 years have passed since last update.

整数をビットの数列に分解する関数 ( 7 を渡したら [1, 2, 4] に分解するやつ )

Posted at
<?php 

function decToBits($dec)
{
    $bin  = decbin($dec);
    $bits = str_split($bin);
    $bits = array_reverse($bits);
    $bits = array_filter($bits);

    foreach ( $bits as $pos => $bit ) {
        $bits[$pos] = pow(2, $pos);
    }

    $bits = array_values($bits);

    return $bits;
}

// テスト用関数
function test()
{
    $bits = func_get_args();
    $sum  = array_sum($bits);

    echo sprintf('Case: %s = %s', $sum, implode(', ', $bits)), PHP_EOL;
    echo json_encode(decToBits($sum)), PHP_EOL;
    echo '---------', PHP_EOL;
}


test(1);
test(1, 2);
test(2, 4);
test(1, 4);
test(1, 2, 4, 8);
test(4, 8);
test(8);
実行結果
Case: 1 = 1
[1]
---------
Case: 3 = 1, 2
[1,2]
---------
Case: 6 = 2, 4
[2,4]
---------
Case: 5 = 1, 4
[1,4]
---------
Case: 15 = 1, 2, 4, 8
[1,2,4,8]
---------
Case: 12 = 4, 8
[4,8]
---------
Case: 8 = 8
[8]
---------
8
7
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7