Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 
", set);
 set = 268304384UL;
 set /= 2;
 printf(" set :%lu 
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...