What does a bitwise shift (left or right) do and what is it used for?

前端 未结 9 2031
傲寒
傲寒 2020-12-02 05:00

I\'ve seen the operators >> and << in various code that I\'ve looked at (none of which I actually understood), but I\'m just wondering

9条回答
  •  有刺的猬
    2020-12-02 05:37

    Left shift: It is equal to the product of the value which has to be shifted and 2 raised to the power of number of bits to be shifted.

    Example:

    1 << 3
    0000 0001  ---> 1
    Shift by 1 bit
    0000 0010 ----> 2 which is equal to 1*2^1
    Shift By 2 bits
    0000 0100 ----> 4 which is equal to 1*2^2
    Shift by 3 bits
    0000 1000 ----> 8 which is equal to 1*2^3
    

    Right shift: It is equal to quotient of value which has to be shifted by 2 raised to the power of number of bits to be shifted.

    Example:

    8 >> 3
    0000 1000  ---> 8 which is equal to 8/2^0
    Shift by 1 bit
    0000 0100 ----> 4 which is equal to 8/2^1
    Shift By 2 bits
    0000 0010 ----> 2 which is equal to 8/2^2
    Shift by 3 bits
    0000 0001 ----> 1 which is equal to 8/2^3
    

提交回复
热议问题