views:

185

answers:

5

For example:

$result = func(14);

The $result should be:

array(1,1,1,0)

How to implement this func?

+3  A: 

decbin would produce a string binary string:

echo decbin(14);                              # outputs "1110"
array_map('intval', str_split(decbin(14)))    # acomplishes the full conversion
SilentGhost
+2  A: 
function func($number) {
    return str_split(decbin($number));
}
too much php
+1  A: 
<?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
)
raspi
+1  A: 

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

Xinus
+1  A: 
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.

Nick