【问题标题】:How to change decimal to binary and restore its bit values to an array?如何将十进制更改为二进制并将其位值恢复为数组?
【发布时间】:2010-11-29 02:08:45
【问题描述】:

例如:

$result = func(14);

$result 应该是:

array(1,1,1,0)

如何实现这个func

【问题讨论】:

    标签: php binary decimal


    【解决方案1】:

    decbin 会产生一个字符串二进制字符串:

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

    【讨论】:

      【解决方案2】:
      function func($number) {
          return str_split(decbin($number));
      }
      

      【讨论】:

        【解决方案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);
        

        输出:

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

        【讨论】:

          【解决方案4】:

          您可以继续将其除以 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

          【讨论】:

            【解决方案5】:
            for($i = 4; $i > 0; $i++){
                array[4-$i] = (int)($x / pow(2,$i);
                $x -= (int)($x / pow(2,$i);
            }
            

            ...这样就可以了。在此之前,您可以检查数组需要多大以及从 $i 的哪个值开始。

            【讨论】:

              猜你喜欢
              • 2019-01-23
              • 2012-01-06
              • 2021-08-29
              • 2021-07-20
              • 1970-01-01
              • 1970-01-01
              • 2021-12-22
              • 1970-01-01
              • 2013-12-26
              相关资源
              最近更新 更多