How to reverse bits of a byte?

前端 未结 8 2492
广开言路
广开言路 2021-02-09 13:09

For example, in PHP, how would I reverse the bits of the byte 11011111 to 11111011?

8条回答
  •  天命终不由人
    2021-02-09 13:39

    This is O(n) with the bit length. Just think of the input as a stack and write to the output stack.

    My attempt at writing this in PHP.

    function bitrev ($inBits, $bitlen){
       $cloneBits=$inBits;
       $inBits=0;
       $count=0;
    
       while ($count < $bitlen){
          $count=$count+1;
          $inBits=$inBits<<1;
          $inBits=$inBits|($cloneBits & 0x1);
          $cloneBits=$cloneBits>>1;
       }
    
        return $inBits;
    }
    

提交回复
热议问题