uint32_t reverseBits(uint32_t n) {
uint32_t m = 0;
for (int i = 0; i < 32; i++, n >>= 1) {
m <<= 1;
m |= n & 1;
}
return m;
}
The process is straightforward, just iterate over all bits.
@xcv58 It would be very helpful if you could explain your approach. From what I understand, you are working like this:
By m<<=1
, you are left-shifting the value of m
by 1 bit in every iteration.
By m|=n&1
, i.e., m=m|n&1
you are checking if the LSB of m
or the LSB of n
is set, in which case you are setting the LSB of m
. Then you move on to the next bit and so on...
However, in what way is this reversing the order of the set bits?
Thank you for your help. I really appreciate it!
@BatCoder Here we get the LSB of n
and set it to m
. On each iteration, we left-shift m
by 1 position. The LSB's of n
become MSB's of m
. This reverses the order of bits. HTH!