~ bitwise operator in JavaScript

I have the following code:

var a = parseInt('010001',2); console.log(a.toString(2)); // 10001 var b = ~a; console.log(b.toString(2)); // -10010 

MSDN Say

~ Executes the NOT operator on each bit. NOT a gives the inverted value (aka of one complement) a.

010001 should return this 101110 .

This topic can confirm that

So, I do not understand how we can get -10010 ? The only possible explanation is that:

010001 is denied 101110, but he writes this -10001 and then for some unknown reason he gave me two additions and -10001 become -10010.

But all this is very unclear in my mind, you would have an idea that this is exactly what is happening.

+6
source share
4 answers

Under the covers, when Javascript performs bitwise operations, it converts to a 32-bit integer and uses it, and then converts the result back to its internal decimal representation.

So your input value 010001 becomes 00000000 00000000 00000000 00010001 .

Then it is inverted:

 ~00000000 00000000 00000000 00010001 => 11111111 11111111 11111111 11101110 

Converted to hexadecimal, inverted value 0xFFFFFFEE , which is equivalent to the decimal value -18.

Since this is a signed integer with a value of -18, this value is converted to a base decimal representation of -18 by Javascript.

When Javascript tries to print it as base number-2, it sees a negative sign and a value of 18 and prints it as -10010 , since 10010 is a binary representation of positive 18.

+2
source

JavaScript bitwise operators convert their operands to 32-bit integers (normal 2 addition ), do their job, and then return the result as the most suitable value in the JavaScript number type (double-precision floating point, JavaScript does not have an integer type). More details in ยง12.5.11 (Bitwise NOT Operator ~ ) and ยง 7.1.5 ( ToInt32 ) .

So your 10001 :

  00000000 00000000 00000000 00010001

which at ~ is equal to:

  11111111 11111111 11111111 11101110

... which is really negative in the 2s complement view.

You may be wondering: if the bit pattern has a value higher, then why did b.toString(2) instead give you -10010 ? Because it shows you a signed binary, not the actual bit. - means negative, and 10010 means 18 decimal places. The bit diagram above is how it is represented in the bits of the 2s complement. (And yes, I had to test myself on this!)

+3
source

JavaScript uses 32-bit signed numbers, so

 a (010001) (17) is 0000 0000 0000 0000 0000 0000 0001 0001 b = ~a (?) (-18) is 1111 1111 1111 1111 1111 1111 1110 1110 

The reason for printing -18 as -10010 and the methods for getting the actual value are well explained here Link

+1
source

According to the documentation on the Mozilla developer website here . The bitwise indication of any number x gives - (x + 1). For example, ~ 5 gives -6. That is why you get a negative sign in front of the number.

0
source

All Articles