Php 如何将十进制改为二进制,并将其位值恢复到数组中?

Php 如何将十进制改为二进制,并将其位值恢复到数组中?,php,binary,decimal,Php,Binary,Decimal,例如: $result = func(14); $result应为: array(1,1,1,0) 如何实现此func?将生成一个字符串二进制字符串: echo decbin(14); # outputs "1110" array_map('intval', str_split(decbin(14))) # acomplishes the full conversion 您可以继续将其除以2,并将余数反向存储 数字=14

例如:

$result = func(14);
$result
应为:

array(1,1,1,0)
如何实现此
func

将生成一个字符串二进制字符串:

echo decbin(14);                              # outputs "1110"
array_map('intval', str_split(decbin(14)))    # acomplishes the full conversion   

您可以继续将其除以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的哪个值开始

<?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
)
for($i = 4; $i > 0; $i++){
    array[4-$i] = (int)($x / pow(2,$i);
    $x -= (int)($x / pow(2,$i);
}