Created
February 17, 2012 06:36
-
-
Save suin/1851318 to your computer and use it in GitHub Desktop.
整数をビットの数列に分解する関数 ( 7 を渡したら [1, 2, 4] に分解するやつ ) ref: http://qiita.com/items/2582
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | |
--------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment