What does 'x << ~y' represent in JavaScript?

前端 未结 5 2060
心在旅途
心在旅途 2020-12-24 02:08

What does \'x << ~y\' represent in JavaScript?

I understand that the bitwise SHIFT operation does this:

x << y AS x * 2y         


        
5条回答
  •  时光取名叫无心
    2020-12-24 02:23

    x << -n is equal to x << (32 - n)
    ~3 == -4 so
    5 << ~3 === 5 << (32 - 4) === 5 << 28 which is 1,342,177,280

    to be accurate X << -n is not the same as X << (32 - n) ... in fact it's both simpler and more complicated ... the valid range of a bit shift operator is 0 to 31 ... the RHS in a bit shift operator is first converted to an unsigned 32 bit integer, then masked with 31 (hex 1f) (binary 11111)

                       3 = 00000000000000000000000000000011  
                      ~3 = 11111111111111111111111111111100
           0x1f (the mask) 00000000000000000000000000011111
                           --------------------------------
                ~3 & 0x1f  00000000000000000000000000011100 = 28
    

    when the magnitude is less than 32, it's exactly the same as what I posted above though

    Bit operations work with 32 bit integers. Negative bit shifts are meaningless so are wrapped into positive 32 bit integers

    How the << operator works

    The rhs is converted to an unsigned 32bit integer - like explained here ToUInt32

    ToUint32 basically takes a number and returns the number modulo 2^32

提交回复
热议问题