javascript bitwise operator question

谁说我不能喝 提交于 2019-11-29 12:38:39

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

~ 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.

From the documentation:

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!