javascript bitwise operator question

前端 未结 4 554
渐次进展
渐次进展 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:02

    ~ toggles the bits of the operand so

    00000001
    

    becomes

    11111110
    

    which is -2

    Note: In javascript, the numbers are 32-bit, but I shortened it to illustrate the point.

    0 讨论(0)
  • 2020-12-20 01:02

    The reason for this is that using a bitwise NOT reverses all the bits of a value. If you are storing the value of 1 in a signed 8-bit integer, you're storing the binary value 00000001. If you apply a bitwise NOT, you get 11111110, which for a signed 8-bit integer is the binary value for -2.

    0 讨论(0)
  • 2020-12-20 01:19

    From the documentation:

    Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题