In JavaScript there is no special type for integer values. Actually, all numbers has a Number
type which is Double Precision Floating Point Number (IEEE 754) i.e. binary64.
One of the problems with numeric operations in JavaScript is that there is no integer division operator or function defined in the standard.
UPDATE: actually, there is a Math.trunc()
function, but it works ~2-5 times slower than binary solution and it's not supported in Internet Explorer.
Some binary operators could be used to achieve the desired result, e.g.:
(10 / 4) >> 0
~~(10 / 4)
(10 / 4) | 0
All operations above produces number 2
and according to my benchmarks, have a similar performance on my x64
machine (Node.js v7.2.1
).
Could you please explain how exactly are those binary operations work for this exact purpose? Is there a preferred one?
First of all, you are convering Numbers to signed 32 bit integers, which means, you lose some digits, compared to 64 bit floating point representation.
The calculation of your numbers is just giving a floating point value of 2.5
and the operands are first converted to a signed 32 bit integer number, then the bitwise calculation takes place. The operand is necessary, because you need it for the initial conversation.
Example for 2 >> 0
Sign-propagating right shift >>
2 (base 10): 00000000000000000000000000000010 (base 2)
--------------------------------
2 >> 0 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
Example for ~~2
Bitwise NOT ~
2 (base 10): 00000000000000000000000000000010 (base 2)
--------------------------------
~2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
--------------------------------
~~2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
Example for 2 | 0
Bitwise OR |
2 (base 10): 00000000000000000000000000000010 (base 2)
0 (base 10): 00000000000000000000000000000000 (base 2)
--------------------------------
2 | 0 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
Beside the possibillity to convert a number to an integer representation, you could use plain Math.floor
for the same purpose and it makes the code not look cryptic.