45
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?

Rotom92
  • 696
  • 1
  • 7
  • 20

5 Answers5

67

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.

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
17

This "right-shift"s the value by one bit. If you move all the bits of an integer to the right by 1 then you effectively "divide by 2" because binary is a base-2 numbering system.

Imagine you have the number 12 in binary:

1100 = 12 in binary
 110 =  6 in binary (1100 right-shifted)

Just like if you moved all of the digits in a base-10 number right by one you would be dividing by 10.

PP.
  • 10,764
  • 7
  • 45
  • 59
6

Every binary operator can be combined with =. In all cases

dest op= expression

is equivalent to

dest = dest op expression

(except if dest has any side effects, they only take place once).

So this means that

set>>=1;

is equivalent to:

set = set >> 1;

Since >> is the binary right-shift operator, it means to shift the value in set right by 1 bit.

Barmar
  • 741,623
  • 53
  • 500
  • 612
4

This shifts bit to the right by 1 which is equivalent to division by 2. For more information on bit shifting, refer to http://msdn.microsoft.com/en-us/library/f96c63ed(v=vs.80).aspx

Ashish Kaila
  • 447
  • 7
  • 11
1

The above command performs right shift by one bit .Refer bit wise operations in c from this link http://www.cprogramming.com/tutorial/bitwise_operators.html

Santhosh Pai
  • 2,535
  • 8
  • 28
  • 49