Bitwise Operator

  • There are six types of Bitwise operators :

& (AND), | (OR) , ^ (X -OR), ~ (COMPLIMENT) , >> (RIGHT SHIFT) , << (LEFT SHIFT)

  • All the operators will not modify the operands.

 

>  Now let us understand the difference between logical AND, OR and Bitwise AND, OR. In Logical operations, compiler will check for both sides operand value whether it is zero or none – zero. So if both side value is one then answer will be true or you can say one.

While in bitwise, compiler will perform the task bit by bit. We will understand this concept of Bitwise operator by taking one example :

 

1.main()

  1. {int i = 10, j = 15 , k ;

    k = i && j;

    printf(“i = %d j = %d k = %d\n”,i,j,k);

     

     

     

    k = i & j;

printf(“i = %d j = %d k = %d\n”,i,j,k);

}

Answer : i =10 , j = 15 , k =1

i =10 , j =15 , k = 10

Now try using table given below :

Untitled Diagram (11).jpg

  • Did you notice the difference? Check last bit (LSB) of i and j.  Anding of 0 and 1 is 0.
  • Similarly, for second to last bit. Anding of 1 and 1 is 1 and so on.
  • Similarly, you can do for ORing and Compliment.

Now, we will discuss Right and Left Shift:

Example : int i = 10 , j = 1 ,  k;

1.   k = i << j;

Answer  :  Here i = 0000 1010

So, if we left shift it by 1 position it becomes 0001 0100

So k = 20 is a correct answer.

2.    k = i >> j;

Answer  :  Here i = 0000 1010

So if we left shift by 1 position it becomes 0000 0101

So k = 5 is a correct answer.

 

 

 

 

 

 

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: