tags:

views:

275

answers:

6

Hi

Confused as to what this code does

for (L=0; L < levels; L++, N_half>>=1){
    func( y, N_half);
} // end: levels for loop

In particular this " N_half>>=1 "

Thanks

+9  A: 

It advances the loop by dividing N_half by two at every iteration. It is equivalent to:

for (L=0; L<levels; ++L, N_half=N_half / 2) {
    ...
}
D.Shawley
Thanks, much appreciated
+5  A: 

N_half>>=1 performs a 1-place bitwise shift-right on N_half, which (for non-negative numbers) divides it by 2.

>>= is to >> as += is to +.

chaos
A: 

If N_half is a positive or unsigned integer, it halves it.

Barry Kelly
Actually, it also works if N_half is negative.
RaphaelSP
RaphaelSP - there is no standard that indicates that twos complement notation must be used. It's only guaranteed to work for unsigned and positive numbers, AFAIK.
Barry Kelly
A: 

It right shifts N_half by 1 (i.e. divides it by two) and stores the result back in N_half

Ronny Vindenes
A: 

This seems to be the same as

for (L=0; L < levels; L++)
{
  func(y, N_Half); 
  N_Half /= 2;
}

The question has been rephrased since I answered it, such that this is no longer valid, but added for completeness: If nothing else is done within the loop, it is equivalent to:

N_Half >>= levels;

Caveats:

  • if N_Half < 2^levels (0 for several iterations)
  • if N_Half < 0 (first rightshift will depending on the implementation make it a positive number)
Ralph Rickenbach
You need to look at the original code again - it did not call 'floor', and the function it called took y as an extra argument.
Jonathan Leffler
Also, the behaviour of right-shift on negative (hence, necessarily, signed) values is not guaranteed to convert the value to positive. The C standard explicitly leaves it up to the implementation and the shift can copy the sign bit or insert zeroes; both are correct (though a given compiler may only use one or the other technique).
Jonathan Leffler
And 'floor()' is a floating point function...
Jonathan Leffler
+1  A: 

>>= operator shifts number's digits k positions at right

examples:

binary form

N = 101010111 // 2-base  arithmetic system
N >>= 1; // `division` by 2
N: 010101011

decimal form

N = 123456 // 10-base  arithmetic system
N >>= 2; // `division` by 10^2
N: 001234

as usual, the numbers in memory are in binary form and >>=1 is equivalent to division by 2.

Nick D
??? How is ">>= 2" division by 100? Your example with decimal representation makes no sense to me. Please clarify?
abelenky
It's the shift operation in the decimal form. Not binary. You cannot apply it with the `standard` >>= unless you have a Class for decimal numbers. Ex. 345 >> 1 is 345/10, 345 >> 2 is (345/10)/10.
Nick D
Ah: an overloaded operator. I've never encountered that type of overloading for >>. Thx.
abelenky