For example, in PHP, how would I reverse the bits of the byte 11011111
to 11111011
?
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 :(