I want to write a program which reverses the bits of an integer.
Ex 11000101 to 10100011
I know how to solve this using a loop, but I came across solutions that do it us
A recursive method for reversing the order of the bits in an integer -- call with the value to be reversed and the width of the value.
procedure int REVERSEBITS( int VALUE; int WIDTH ) {
if WIDTH==1 then {
return VALUE;
} else {
// intermediate values may help make the algorithm more understandable
int HalfWidth = WIDTH >> 1; // number of bits to be swapped at this level
int HalfMask = HalfWidth-1; // mask for left or right half of the value
int RightHalfValue = VALUE & HalfMask; // extract right half from value
int LeftHalfValue = (VALUE >> HalfWidth) & HalfMask; // extract left half
// call reversing function on the two halves separately then swap the results
return (REVERSEBITS(RightHalfValue, HalfWidth) << HalfWidth)
| REVERSEBITS(LeftHalfValue, HalfWidth);
}
}
Or, shorten the function by replacing all intermediate values with their definitions (optimizing compilers will usually produce the same code either way)
procedure int REVERSEBITS( int VALUE; int WIDTH ) {
if WIDTH==1 then {
return VALUE;
} else {
return (REVERSEBITS((VALUE & ((WIDTH>>1)-1)), (WIDTH>>1)) << (WIDTH>>1))
| REVERSEBITS(((VALUE >> (WIDTH>>1)) & ((WIDTH>>1)-1)), (WIDTH>>1));
}
}
Simplify the function code slightly by changing the functional definition, i.e. call with the value to be reversed and HALF the width of the value
procedure int REVERSEBITS( int VALUE; int WIDTH ) {
if WIDTH==0 then {
return VALUE;
} else {
return (REVERSEBITS((VALUE & (WIDTH-1)), (WIDTH >> 1)) << WIDTH)
| REVERSEBITS(((VALUE >> WIDTH) & (WIDTH-1)), (WIDTH >> 1));
}
}