Borak - software developer illustrational
Blog
27.4. 2021 / 23:42

javascript

front end

Javascript tilde - bitwise not operator

Man sometimes comes to the situations, that are so beyond his grasp, that he cannot but call it magic. I will try to explain one such concept that seemed to me this way a few years ago.

Javascript BITWISE NOT operator.

The most famous use case for tilde (Bitwise not operator) had been the detection of whether a value is included in an Array:

!!~[1,3,].indexOf(0) // returns FALSE
!!~[1,3].indexOf(1) // returns TRUE
When tilde is applied to an integer, it returns

~N => -(N+1)
The magic behind this formula comes from the way the numbers are internally represented in Javascript. The Number in Javascript is stored according to  definition IEEE 754 – Double decimal number.

For binary operators (including binary NOT operator aka tilde) the number is trimmed to closest lower absolute value and then casted to 32 bit signed integer.

The 32 bit signed integer is represented by 32 slots in binary – so 32 occurences of either 0 or 1. The first half of the values represented by this sequence of 32 bits is representing negative numbers. That’s called offset.

E.g.:
If we had four bit integer with negative numbers defined by offset, the negative numbers would be the first half of the values:

1111 to 1000

And the other half would be the positive numbers:

0000 to 0111
So, -1 would be 1000
And +1 would be 0001

There is one more concept to grasp –

Twos complement

If you have this set of bits:

0001
The twos complement is the set of bits that, for bitwise AND operation resets the previous value to 0000.
In this case, the twos complement is
1111

Because
1111
AND
0001
=
1 (this bit will overflow)0000

Let’s say, we have number 2,1
For the formula ~2,1, the Javascript engine does the following
  • Trim the absolute value to nearest smaller whole absolute value:
    • 2
  • Express the number with sign (2) as 32 bit signed integer
    • 00000000000000000000000000000010
  • Negate the value by bit negation operation
    • 11111111111111111111111111111101
  • This value:  11111111111111111111111111111101
  • Is twos complement to: 00000000000000000000000000000011
  • Which is 3 in decimal

That’s it

~2.1
IsĀ 
-3.

More by Borak

To maximalize your user experience during visit to my page, I use cookies.More info
I understand

#BORAKlive

This page is subjected to the Creative Common Licence. Always cite the Author - Do not use the page's content on commercial basis. Comply with the licence 3.0 Czech Republic.
go to top