Zhongde Liu

This is my personal "Clipboard" of web development stuff I come across

Code: “cast a number to int” with bitwise operators

Leave a comment

In order to cast a number to an int value you can also use bit operations. In particular the Double NOT and the OR 0.

~~(3.14) // => 3
3.14 | 0 // => 3

As these operations are working on on signed 32-bit integers per default, the number is in fact truncated after the comma. This also works on negative numbers.

~~(-3.14) // => -3
-3.14 | 0 // => -3

You are asking Why? Why should anyone bother bitwise operators? one word: Performace. If you are crunching a lot, I mean, a lot, numbers, you should notice something. I made a quick jsperf http://jsperf.com/parseint-and-bitwise-operations. You see the bit operations are more than 10x faster than parseInt.

Sidenote: Math.floor is also pretty fast. However Math.floor results in a different result number when used with negative ones.

Math.floor(-3.14) // => -4
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s