简体   繁体   中英

linux kernel code “>>” operator

We've been given an assignment to make some modifications to Linux kernel code and recompile it. I'm having hard time figuring out what does this code line do:

p->time_slice = (current->time_slice + 1) >> 1;

To be more exact, why there's ">> 1" at the end?

">>" means to shift the value bitwise to the right. "x >> y" is the same as dividing by 2^y and truncating the result. Truncating the result means rounding down in almost all cases, however with negative numbers there may exist alternate implementations. Please see comments if you think this is happening to you.

That's a bitwise shift operator. Treating a value as an array of bits, it shifts everything one bit to the right (towards the least significant bit). This is the equivalent of dividing by 2, rounded down, for positive numbers. Shifting is used as a quick way to divide by a power of 2; if you shift by 1 ( >> 1 ), you are dividing by 2, if you shift by 2 ( >> 2 ), you are dividing by 4, and so on.

For example, here are a couple of examples of how this would work, if you were using 4 bit integers:

6 >> 1
  0110  ->  0011 
               3

7 >> 1
  0111  ->  0011
               3

6 >> 2
  0110  ->  0001
               1

For negative numbers, it is a bit more complicated. The C standard does not specify the format of negative numbers. On most modern machines, they are stored in two's complement ; that is, to represent a negative number, you take the positive representation, invert every bit, and add 1. The most significant bit is then taken to indicate the sign bit. If you right shift a negative number, there are two possible interpretations; one in which you always shift a 0 into the most significant bit, one in which you shift in a matching value to what was already there, known as "sign extension."

-2 >> 1
   1110  ->  0111
                7
   1110  ->  1111
               -1

The C standard does not specify which of these interpretations an implementation must use. GCC does the more expected one, sign extension, which is equivelent to dividing by two and rounding down, just like the positive case. Note that rounding down means "towards negative infinity", not "towards zero" as you might assume.

-3 >> 1
   1101  ->  1110
               -2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM