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?
Since >> is the binary right-shift operator, it means to shift the value in set right by 1 bit.
The << operator shifts the left-hand value left by the (right-hand value) bits. Your example does nothing! 1 shifted 0 bits to the left is still 1. However, 1 << 1 is 2, 1 << 2 is 4, etc.
The bitwise shift operators are the right-shift operator (>>), which moves the bits of shift_expression to the right, and the left-shift operator (<<), which moves the bits of shift_expression to the left.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With