An Unusual and Fast Bit Reverse Routine
A function to reverse the order of bits in a byte makes for a good interview question. The candidate has to think about loops, shifting and masking as well as the mundane but important issues of function and variable naming, data types, spacing and comments. As opposed to those "gotcha" questions apparently beloved by the tech giants where you have to know some trick, this can be worked through methodically. Once there is a solution on the table, there is an opportunity to talk about optimization for speed and/or space. There are lots of ways to approach this problem, but I suspect that many will take this simple idea of testing each bit and setting the LSB of the output in a loop which shifts up the output and mask one place each time. //bit reverse eg 0x80 return x01 //simple but straightforward approach uint8_t bitreverse_simple(uint8_t input) { uint8_t i, output, mask; output = 0; mask = 0x01; for (i = 8;i > 0;i--) { output <<= 1; if (input & mask) { output |= 1; } mask <<= 1; } return output; }; Testing The Simple Approach First we need to test that this produces correct results by running…
Continue reading...