公告
财富商城
积分规则
提问
发文
2019-07-20 19:55发布
Fickle 薄情
For example:
$result = func(14);
The $result should be:
$result
array(1,1,1,0)
How to implement this func?
func
<?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);
Output:
Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 0 )
function func($number) { return str_split(decbin($number)); }
You can go on dividing it by 2 and store remainder in reverse...
number=14
14%2 = 0 number=14/2= 7
7%2 = 1 number=7/2 = 3
3%2 = 1 number=3/2 = 1
1%2 = 1 number=1/2 = 0
decbin would produce a string binary string:
decbin
echo decbin(14); # outputs "1110" array_map('intval', str_split(decbin(14))) # acomplishes the full conversion
for($i = 4; $i > 0; $i++){ array[4-$i] = (int)($x / pow(2,$i); $x -= (int)($x / pow(2,$i); }
...this would do the trick. Before that you could check how big the array needs to be and with which value of $i to start.
最多设置5个标签!
Output:
You can go on dividing it by 2 and store remainder in reverse...
number=14
14%2 = 0 number=14/2= 7
7%2 = 1 number=7/2 = 3
3%2 = 1 number=3/2 = 1
1%2 = 1 number=1/2 = 0
decbin
would produce a string binary string:...this would do the trick. Before that you could check how big the array needs to be and with which value of $i to start.