This question already has an answer here:
I understand that ~ is a bitwise NOT operator, but how does inverting the bits on a number twice make it function as Math.floor What does ~~ ("double tilde") do in Javascript? describes the differences between using Math.floor vs bitwise operations to round numbers in Javascript, but I am interested in how exactly inverting the bits twice accomplishes this.
Thanks
It's essentially the equivalent of a truncate function (in the sense that it is casting the float into an integer, which does exactly that), which JavaScript does not have. This is why for negative numbers the behavior is actually closer to
Math.ceil
.From the spec, Bitwise NOT,
~
Definition of
ToInt32
here.The "complement" of a 32-bit integer
i
isi XOR 0xFFFFFFFF
.So put this all together and you have
~~i
as meaningKeep in mind the differences in rounding direction for negative numbers.
Personally I prefer using
x | 0
over~~x
because it involves fewer operations for the same result.~
forces the operand to get cast to an integer. It's a trick to work around the fact that Javascript has no direct way of casting between floating point and integer values. In fact, Javascript doesn't officially have an integer-only type, but implementations are likely to use integers internally for performance.So
~x
is the bitwise inverse ofcastToInt(x)
. Then you inverse the bits again to get justcastToInt(x)
.It happens that casting floating point numbers to integer behaves almost like
Math.floor
. The most notable difference is that casting rounds towards zero, whileMath.floor
rounds towards negative infinity. There are some other differences as well: