Most of us rarely use bit wise operators but if we know where and when to use them they are really going to be awesome.., Let’s check out an application of bit wise operators right now:)

Bit Vectors(series of bits) can be used to represent sets(gotta remember from school days mathematics).

Lets say we have to perform union operation of two sets It becomes increasingly easy if you use bit wise operators

Ex.:

lets say the set we have is {0,3,5,6}

then represent it as follows i.e 7654321 and corresponding status 01101001 where 1 represents the presence of the number in the set and viceversa

Let’s take another set {0,2,4,6}

which is represented as 7654321 and corresponding status 01010101

Now union of two sets is bit wise union( | ) of two statuses and intersection is bit wise intersection( & ) of two statuses and Now Symmetric difference is similarly with bit wise operator ^(exclusive or) and for compliment operator we can use ~ operator on statuses

A smarter Application of bitwise operators

Suppose If you would like to represent if-else conditional in a smarter way Check

out here..,

if(x)

a=y;

else

a=z;

Way one is this **a=x?y:z**

The other interesting way is:

**a= ((x<<31)>>31)&y+(((!x)<<31)>>31)&z**

Here we assumed that the boolean x is either 1 or zero

Another Application is here:

Suppose you are asked to swap two numbers without using a third variable here bit wise operators comet to our rescue i.e An important concept here is if you xor a n bit binary number with any arbitary number twice you get that back the original number; Say you have to swap x and y:

**int x=53,y=43;**

**x=x^y;**

**y=x^y;**

**x=x^y; // “^” operator is associative**