Answer the question
In order to leave comments, you need to log in
What is happening in this code?
Explain what happens in the for loop of the bitrev function
#include <stdio.h>
unsigned bitrev(unsigned n)
{
unsigned r;
for (r = 0; n; n >>= 1) {
r <<= 1;
r |= n & 1;
}
return r;
}
int main()
{
unsigned n;
unsigned n;
scanf("%u", &n);
printf("%u\n", bitrev(n));
return 0;
}
Answer the question
In order to leave comments, you need to log in
The expression
That is, this expression generally takes the least significant bit of the variable n and puts it into the variable r.
As the name of the function suggests, it flips the bits of a number.
100111011 = 315 flips to 110111001 = 441
In the for loop, the current bit of the result is filled - first shifted by a bit, and this bit is filled with the current bit on the right of the original number.
It turns out that in the for loop, the bits flow from the number n to the number r. With each cycle, n is shifted by a bit and that bit is set to the added bit r.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question