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