0

I'm trying to understand the following code that written in C. I found a few lines that are difficult to understand.

unsigned long reflect (unsigned long crc, int bitnum) {
  // reflects the lower 'bitnum' bits of 'crc'
  unsigned long i, j=1, crcout=0;
  for (i=(unsigned long)1<<(bitnum-1); i; i>>=1)
  {
    if (crc & i) crcout|=j;
      j<<= 1;
  }
  return (crcout);
}

In this subroutine, I don't understand the for loop why the second parameter only i, also why and what does this mean: i>>=1? How is this loop evaluated here?

Could someone help me here to understand it And MAYBE give an example in C# as I'm familiar with it? I need to implement this function into my PLC program.

Ruslan
  • 18,162
  • 8
  • 67
  • 136
T.Saleh
  • 35
  • 6
  • 2
    `i` by itself is equivalent to `i != 0` and `i>>=1` shifts `i` right 1, same as `i = i >> 1`. – 001 Jan 28 '21 at 15:53
  • 2
    See [shift operators](https://en.cppreference.com/w/c/language/operator_arithmetic#Shift_operators) and [assignment operators](https://en.cppreference.com/w/c/language/operator_assignment). – Ruslan Jan 28 '21 at 15:53
  • 1
    `for (i=(unsigned long)1<<(bitnum-1); i; i>>=1)` is the same as `for (i = (unsigned long)1 << (bitnum-1); i != 0; i = i >> 1)`. – Jabberwocky Jan 28 '21 at 15:58
  • What does that code mean? A failed code review in any environment that cares about readability, maintainability, reliability, and actually preventing bugs. Remember that anyone saying that code is acceptable has never been responsible for being on 24x7 call for anything important. – Andrew Henle Jan 28 '21 at 16:46
  • @AndrewHenle believe it or not, if I was able to figure it out by myself or with google search I would not ask it here! – T.Saleh Jan 28 '21 at 17:01
  • 2
    @MesopotamianLion My point was that when what code does isn't clear, and you can't see what it does without a lot of effort, ***it's bad code*** that should never get introduced into any code base. The fact that this code comes from some code base you found means that the environment that created that code has low standards and likely produces unreliable products. – Andrew Henle Jan 28 '21 at 17:03
  • Does this answer your question? [Understanding the exit condition of a 'for' loop](https://stackoverflow.com/questions/9204018/understanding-the-exit-condition-of-a-for-loop) – the busybee Jan 28 '21 at 20:17

0 Answers0