【发布时间】:2010-11-29 02:08:45
【问题描述】:
例如:
$result = func(14);
$result 应该是:
array(1,1,1,0)
如何实现这个func?
【问题讨论】:
例如:
$result = func(14);
$result 应该是:
array(1,1,1,0)
如何实现这个func?
【问题讨论】:
decbin 会产生一个字符串二进制字符串:
echo decbin(14); # outputs "1110"
array_map('intval', str_split(decbin(14))) # acomplishes the full conversion
【讨论】:
function func($number) {
return str_split(decbin($number));
}
【讨论】:
<?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
)
【讨论】:
您可以继续将其除以 2 并将余数反向存储...
数字=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
【讨论】:
for($i = 4; $i > 0; $i++){
array[4-$i] = (int)($x / pow(2,$i);
$x -= (int)($x / pow(2,$i);
}
...这样就可以了。在此之前,您可以检查数组需要多大以及从 $i 的哪个值开始。
【讨论】: