How to reverse bits of a byte?

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

    If you have already the bits in the form of a string, use strrev.

    If not, convert first the byte to its binary representation by using decbin, then reverse using strrev, then go back to byte (if necessary) by using bindec.

    0 讨论(0)
  • 2021-02-09 13:24

    I disagree with using a look up table as (for larger integers) the amount of time necessary to load it into memory trumps processing performance.

    I also use a bitwise masking approach for a O(logn) solution, which looks like:

    MASK = onescompliment of 0    
    while SIZE is greater than 0
      SIZE = SIZE shiftRight 1
      MASK = MASK xor (MASK shiftLeft SIZE)
      output = ((output shiftRight  SIZE) bitwiseAnd MASK) bitwiseOR ((onescompliment of MASK) bitwiseAnd (output shfitLeft SIZE))
    

    The advantage of this approach is it handles the size of your integer as an argument

    in php this might look like:

    function bitrev($bitstring, $size){
    
      $mask = ~0;
      while ($size > 0){
    
        $size = $size >> 1;
        $mask = $mask ^ ($mask << $size);
        $bitstring = (($bitstring >> $size) & $mask) | ((~$mask) & ($bitstring << $size));
      }
    }
    

    unless I screwed up my php somewhere :(

    0 讨论(0)
  • 2021-02-09 13:27

    The straight forward approach is to perform 8 masks, 8 rotates, and 7 additions:

    $blah = $blah & 128 >> 7 + $blah & 64 >> 5 + $blah & 32 >> 3 + $blah & 16 >> 1 + $blah & 8 << 1 + $blah & 4 << 3 + $blah & 2 << 5 + $blah & 1 << 7;
    
    0 讨论(0)
  • 2021-02-09 13:34

    Try to get this book, there is whole chapter about bits reversion: Hacker's Delight. But please check content first if this suits you.

    0 讨论(0)
  • 2021-02-09 13:36

    Check the section on reversing bit sequences in Bit Twiddling Hacks. Should be easy to adapt one of the techniques into PHP.

    While probably not practical for PHP, there's a particularly fascinating one using 3 64bit operations:

    unsigned char b; // reverse this (8-bit) byte
    b = (b * 0x0202020202ULL & 0x010884422010ULL) % 1023;
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题