What does this ">>=" operator mean in C?

c

Solution

The expression `set >>= 1;` means `set = set >> 1;` that is right shift bits of `set` by `1` (self assigned form of `>>` bitwise right shift operator check Bitwise Shift Operators).

Suppose if `set` is:

BIT NUMBER    31   n=27        m=17                 0
              ▼    ▼           ▼                    ▼
set =         0000 1111 1111 1110 0000 0000 0000 0000

Then after `set >> = 1;` variable `set` becomes:

BIT NUMBER    31   n=26        m=16                 0
              ▼     ▼           ▼                   ▼
set =         0000 0111 1111 1111 0000 0000 0000 0000

Notice the bits number shifted.

Note a interesting point: Because `set` is `unsigned long` so this `>>` operation should be logical shift( unsigned shift) a logical shift does not preserve a number's sign bit.

Additionally, because you are shifting all bits to right (towards lower significant number) so one right shift is = divide number by two.

check this code (just to demonstrate last point):

int main(){
 unsigned long set = 268304384UL;
 set >>= 1;
 printf(" set :%lu \n", set);
 set = 268304384UL;
 set /= 2;
 printf(" set :%lu \n", set);
 return 1; 
}

And output:

 set :134152192 
 set :134152192

(note: its doesn't means `>>` and `/` are both same)

Similarly you have operator `<<=` for left shift, check other available Bitwise operators and Compound assignment operators, also check section: bit expressions and difference between: signed/arithmetic shift and unsigned shift.

Problem

``` unsigned long set; /*set is after modified*/ set >>= 1; ``` I found this in a kernel system call but I don't understand, how does it work?

Original source

Related problems