2

For example:

$result = func(14);

The $result should be:

array(1,1,1,0)

How to implement this func?

5 Answers 5

5

decbin would produce a string binary string:

echo decbin(14);                              # outputs "1110"
array_map('intval', str_split(decbin(14)))    # acomplishes the full conversion   
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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);

Output:

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

Comments

1

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

Comments

1
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.