Most efficient way to extract bit flags

后端 未结 5 738
旧巷少年郎
旧巷少年郎 2021-01-02 10:08

I have these possible bit flags.

1, 2, 4, 8, 16, 64, 128, 256, 512, 2048, 4096, 16384, 32768, 65536

So each number is like a true/false sta

5条回答
  •  醉话见心
    2021-01-02 10:58

    As there is no definite answer with php code, I add this working example:

    // returns array of numbers, so for 7 returns array(1,2,4), etc..
    
    function get_bits($decimal) {
      $scan = 1;
      $result = array();
      while ($decimal >= $scan){
        if ($decimal & $scan) $result[] = $scan;
        $scan<<=1; 
      }
      return $result;
    }
    

提交回复
热议问题