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

前端 未结 9 2033
傲寒
傲寒 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:44

    Left Shift

    x = x * 2^value (normal operation)

    x << value (bit-wise operation)


    x = x * 16 (which is the same as 2^4)

    The left shift equivalent would be x = x << 4

    Right Shift

    x = x / 2^value (normal arithmetic operation)

    x >> value (bit-wise operation)


    x = x / 8 (which is the same as 2^3)

    The right shift equivalent would be x = x >> 3

    0 讨论(0)
  • 2020-12-02 05:49

    Here is an applet where you can exercise some bit-operations, including shifting.

    You have a collection of bits, and you move some of them beyond their bounds:

    1111 1110 << 2
    1111 1000
    

    It is filled from the right with fresh zeros. :)

    0001 1111 >> 3
    0000 0011
    

    Filled from the left. A special case is the leading 1. It often indicates a negative value - depending on the language and datatype. So often it is wanted, that if you shift right, the first bit stays as it is.

    1100 1100 >> 1
    1110 0110
    

    And it is conserved over multiple shifts:

    1100 1100 >> 2
    1111 0011
    

    If you don't want the first bit to be preserved, you use (in Java, Scala, C++, C as far as I know, and maybe more) a triple-sign-operator:

    1100 1100 >>> 1
    0110 0110
    

    There isn't any equivalent in the other direction, because it doesn't make any sense - maybe in your very special context, but not in general.

    Mathematically, a left-shift is a *=2, 2 left-shifts is a *=4 and so on. A right-shift is a /= 2 and so on.

    0 讨论(0)
  • 2020-12-02 05:52

    Here is an example:

    #include"stdio.h"
    #include"conio.h"
    
    void main()
    {
        int rm, vivek;
        clrscr();
        printf("Enter any numbers\t(E.g., 1, 2, 5");
        scanf("%d", &rm); // rm = 5(0101) << 2 (two step add zero's), so the value is 10100
        printf("This left shift value%d=%d", rm, rm<<4);
        printf("This right shift value%d=%d", rm, rm>>2);
        getch();
    }
    
    0 讨论(0)
提交回复
热议问题