How to change decimal to binary and restore its bi

2019-07-20 19:55发布

For example:

$result = func(14);

The $result should be:

array(1,1,1,0)

How to implement this func?

5条回答
Lonely孤独者°
2楼-- · 2019-07-20 20:09
<?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
)
查看更多
Fickle 薄情
3楼-- · 2019-07-20 20:10
function func($number) {
    return str_split(decbin($number));
}
查看更多
叼着烟拽天下
4楼-- · 2019-07-20 20:12

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

查看更多
▲ chillily
5楼-- · 2019-07-20 20:14

decbin would produce a string binary string:

echo decbin(14);                              # outputs "1110"
array_map('intval', str_split(decbin(14)))    # acomplishes the full conversion   
查看更多
甜甜的少女心
6楼-- · 2019-07-20 20:25
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.

查看更多
登录 后发表回答