How to reverse bits of a byte?

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

    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 :(

提交回复
热议问题