javascript bitwise operator question

前端 未结 4 564
渐次进展
渐次进展 2020-12-20 00:24

In Javascript when I do this

var num = 1;

~ num == -2

why does ~num not equal 0

in binary 1 is st

4条回答
  •  一整个雨季
    2020-12-20 01:28

    Look up Two's complement for signed binary numbers

    Lets assume that a javascript Number is 8 bits wide (which its not):

    then

    1 = 0000 0001b
    

    and

    ~1 = 1111 1110b
    

    Which is the binary representation of -2

    0000 0010b =  2
    0000 0001b =  1
    0000 0000b =  0
    1111 1111b = -1
    1111 1110b = -2
    

提交回复
热议问题