What do these JavaScript bitwise operators do?

后端 未结 3 2084
余生分开走
余生分开走 2020-11-22 10:36
  • x <<= y (x = x << y)
  • x >>= y (x = x >> y)
  • x >>>= y (x = x >>> y)
3条回答
  •  甜味超标
    2020-11-22 11:13

    Here is an attempt to make things simple for the very beginner.

    Prerequisites

    You have to be familiar with the binary number system (numbers made of two digits). If you are not then check this link first: https://www.mathsisfun.com/binary-number-system.html. Just in case the previous link breaks, this answer may help a little: https://stackoverflow.com/a/32155850/1636522.

    Indeed, in order to figure out how these operators work, you need to know which bit sequence is behind the numbers involved in the operation. After that you should be able to understand the following stuffs.

    Reminder

    Decimal digits and their binary notations:

    0    0 | 5  101
    1    1 | 6  110
    2   10 | 7  111
    3   11 | 8 1000
    4  100 | 9 1001
    

    What do >>>, >> and << do?

    These operators shift a bit sequence to the left or to the right.

     decimal | binary      decimal | binary 
    ---------|---------   ---------|---------
           9 |    1001           2 |      10
        >> 2 | >>    2        << 2 | <<    2
         = 2 |  =   10         = 8 |  = 1000
    

    What do &, | and ^ do?

    These operators combine the bits of two numbers to create a new number.

     decimal | binary     decimal | binary     decimal | binary
    ---------|--------   ---------|--------   ---------|--------
           5 |    101           5 |    101           5 |    101
         & 6 |  & 110         | 6 |  | 110         ^ 6 |  ^ 110
         = 4 |  = 100         = 7 |  = 111         = 3 |  = 011
    

    How does & work?

    For each pair of bits: If at least one of the two bits is 0, the resulting bit is 0. If none of the two bits is 0, the resulting bit is 1.

      101    bit 3 | bit 2 | bit 1
    & 110   -------|-------|-------
    = 100      1   |   0   |   1
               &   |   &   |   &
               1   |   1   |   0
               =   |   =   |   =
               1   |   0   |   0
    

    How does | work?

    For each pair of bits: If at least one of the two bits is 1, the resulting bit is 1. If none of the two bits is 1, the resulting bit is 0.

      101    bit 3 | bit 2 | bit 1
    | 110   -------|-------|-------
    = 111      1   |   0   |   1
               |   |   |   |   |
               1   |   1   |   0
               =   |   =   |   =
               1   |   1   |   1
    

    How does ^ work?

    For each pair of bits: If the two bits are different, the resulting bit is 1. If the two bits are the same, the resulting bit is 0.

      101    bit 3 | bit 2 | bit 1
    ^ 110   -------|-------|-------
    = 011      1   |   0   |   1
               ^   |   ^   |   ^
               1   |   1   |   0
               =   |   =   |   =
               0   |   1   |   1
    

提交回复
热议问题