Can you explain code?

Can you explain what exactly exp >>= 1 does in the code bellow?

1
2
3
4
5
6
7
8
9
10
11
12
13
int ipow(int base, int exp)
{
    int result = 1;
    while (exp)
    {
        if (exp & 1)
            result *= base;
        exp >>= 1;
        base *= base;
    }
  return result;
}
>>= is the compound assignment operator for the shift right operator >>

Line 8 is the same as writing exp = (exp >> 1);

Line 9 also uses a compound assignment operator ;)

cnoeval links to some useful pages below.
Last edited on
I could not understand why they shift the bit to right. But it's clear to me now how it works. The trick is that this is like counter, but in opposite direction.

Not tested but I think this should do the same in opposite direction:
1
2
3
4
5
6
7
8
9
10
11
12
13
int ipow2(int base, int exp)
{
    int result = 1;
    int n=0;
    for (;n<exp;n++)
    {
        if (n & 1)
            result *= base;
        n <<= 1;
        base *= base;
    }
  return result;
}


Edit: no, it does not work.

I tried to debug the function ipow in codeblock and I have found something strange. When I place break on line 6 and use f7 to go to next line, it temporally jumps to line 8 and then it immediately goes back to line 7 instead to stay on line 8. Maybe some bug in IDE.
Last edited on
Topic archived. No new replies allowed.