javascript bitwise operator question

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

    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.

提交回复
热议问题