B
B
bellau2014-06-22 22:18:38
C++ / C#
bellau, 2014-06-22 22:18:38

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;
}

I understand the purpose of the function.
I can't figure out what the line r |= n & 1; is doing.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Popov, 2014-06-23
@bellau

The expression
That is, this expression generally takes the least significant bit of the variable n and puts it into the variable r.

S
Sumor, 2014-06-22
@Sumor

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 question

Ask a Question

731 491 924 answers to any question