How to reverse bits of a byte?

前端 未结 8 2508
广开言路
广开言路 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:41

    The quickest way, but also the one requiring more space is a lookup, whereby each possible value of a byte (256 if you go for the whole range), is associated with its "reversed" equivalent.

    If you only have a few such bytes to handle, bit-wise operators will do but that will be slower, maybe something like:

    function reverseBits($in) {
      $out = 0;
    
      if ($in & 0x01) $out |= 0x80;
      if ($in & 0x02) $out |= 0x40;
      if ($in & 0x04) $out |= 0x20;
      if ($in & 0x08) $out |= 0x10;
      if ($in & 0x10) $out |= 0x08;
      if ($in & 0x20) $out |= 0x04;
      if ($in & 0x40) $out |= 0x02;
      if ($in & 0x80) $out |= 0x01;
    
      return $out;
    }
    

提交回复
热议问题