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)
– 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.
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 –
If you have this set of bits:
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
1 (this bit will overflow)0000
Let’s say, we have number 2,1
- Trim the absolute value to nearest smaller whole absolute value:
- Express the number with sign (2) as 32 bit signed integer
- Negate the value by bit negation operation
- This value: 11111111111111111111111111111101
- Is twos complement to: 00000000000000000000000000000011
- Which is 3 in decimal