Can anyone explain why '>>2' shift means 'divided by 4' in C codes?

后端 未结 10 1497
谎友^
谎友^ 2020-12-05 09:25

I know and understand the result.

For example:


7 (decimal) = 00000111 (binary)
and 7 >> 2 = 00000001 (binary)
10条回答
  •  我在风中等你
    2020-12-05 09:39

    It is actually defined that way in the C standard.

    From section 6.5.7:

    The result of E1 >> E2 is E1 right-shifted E2 bit positions. [...] the value of the result is the integral part of the quotient of E1 / 2E2

    On most architectures, x >> 2 is only equal to x / 4 for non-negative numbers. For negative numbers, it usually rounds the opposite direction.

    Compilers have always been able to optimize x / 4 into x >> 2. This technique is called "strength reduction", and even the oldest compilers can do this. So there is no benefit to writing x / 4 as x >> 2.

提交回复
热议问题