Some alternative use of bit wise operators

In this blog, I am just going to share some of the alternative use of the bitwise operators.

1. Replace Math.floor with double ~~.
Even though JavaScript Math library is well optimized, we can use the bitwise operators to reduce some keystrokes.

~~3.4 //result : 3

2. Convert to Boolean using !!
Double NOT operator is used to convert any type into Boolean.

var d = "Hi";
!!d //result : true
var f = null;
!!f //result : false

3. Swap values without temp variable using XOR.
It is the one of the common method used to swap two variables without using temp variable.

var a = 5, b= 6;
a ^= b; b ^= a; a ^= b; //result a = 6, b = 5;

4. Using left and right shift with 1 bit to perform multiply and division.
Left shifting a number 1 bit is equivalent to the result obtained by multiplying it by 2 and right shifting 1 bit is equivalent to dividing it by 2.

var d = 4, f = 6;
d >> 1 //result : 4 * 2 = 8
f << 1 //result : 6 / 2 = 3

5. Checking odd/even using AND with 1
Performing AND operation with 1 will return value greater than 0 if its odd. We can use it simply to find whether a number is odd or even.

var a = 5, b= 6;
a & 1//result 1 - odd
b & 1//result 0 - even

Happy Scripting…

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