2009-09-17 29 views

回答

3
function func($number) { 
    return str_split(decbin($number)); 
} 
5

decbin會產生一個字符串二進制字符串:

echo decbin(14);        # outputs "1110" 
array_map('intval', str_split(decbin(14))) # acomplishes the full conversion 
1
<?php 
function int_to_bitarray($int) 
{ 
    if (!is_int($int)) 
    { 
    throw new Exception("Not integer"); 
    } 

    return str_split(decbin($int)); 
} 

$result = int_to_bitarray(14); 
print_r($result); 

輸出:

Array 
(
    [0] => 1 
    [1] => 1 
    [2] => 1 
    [3] => 0 
) 
1

你可以繼續將其除以2並存儲剩餘反...

number = 14

14%2 = 0數= 14/2 = 7

7%2 = 1數= 7/2 = 3

3%2 = 1號= 3/2 = 1

1%2 = 1號= 1/2 = 0

1
for($i = 4; $i > 0; $i++){ 
    array[4-$i] = (int)($x/pow(2,$i); 
    $x -= (int)($x/pow(2,$i); 
} 

...這將達到目的。在此之前,您可以檢查數組的大小以及$ i開始的值。

相關問題