Regarding the first half:
>>
is a bitwise shift to the right.
Thus, a shift of a numerical value of 3 bits to the right will be the same as dividing by 8 and int
by the result.
Here is a good link for operators and their priority: http://web.cs.mun.ca/~michael/c/op.html
The second part of your question is related to the &
operator, which is a bit-muddy I. Example: ANDing i
and a number that leaves all the bits except the three least significant. This is essentially the same thing when you have a number, divide it by 8, save the result as an integer, then multiply this result by 8.
The reason for this is that dividing by 8 and storing as an integer is the same as shifting bits to the right 3 places, and multiplying by 8 and storing the result in int is the same as shifting bits to the left 3 places.
So, if you multiply or divide by 2, for example 8, and you agree with the truncation of bits that occur when you store this result in int
, the bit shift is faster, faster. This is because the processor can skip the multiplication / division algorithm and just go to the offset bits, which includes several steps.
source share