How to change decimal to binary and restore its bit values to an array?

僤鯓⒐⒋嵵緔 提交于 2019-12-24 00:05:18

问题


For example:

$result = func(14);

The $result should be:

array(1,1,1,0)

How to implement this func?


回答1:


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



回答2:


decbin would produce a string binary string:

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



回答3:


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



回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/1437670/how-to-change-decimal-to-binary-and-restore-its-bit-values-to-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!