Everything you need to know about bitwise operator in C programming

Bitwise operators in C
- It is used to manipulate data at bit level.
- It can applied only to integer operand.

Types :

1. Bitwise Logical Operator
    -Bitwise AND (&) : both true, true, else false
    -Bitwise OR  (|) : either 1 true, true, else false
    -Bitwise XOR (^) : same digit 0, else 1

#include<stdio.h>
int main(){
int a,b,c,d,e;
a=50;                   //50 =   0000 0000 0011 0010
b=20;                  // 20 =  0000 0000 0001 0100
c=(a&b);         //(a&b)=   0000 0000 0001 0000 : 16
d=(a|b);           // (a|b)=  0000 0000 0011 0110  : 54
e=(a^b);         //(a^b)=   0000 0000 0010 0110 : 38

printf("%d %d %d",c,d,e); 

As you can see, we have performed bitwise AND(&), OR(|) and XOR(^) and got the output as 16, 54 and 38 respectively.               


2. Bitwise Shift Operator : used to move bit patterns either left or right.
    - Left Shift  (<<) : causes operand to be shifted to the left by specified bit position
    - Right Shift (>>) : causes operand to be shifted to the right by specified bit position

int a,b,c;
a=50;                   //50 =       0000 0000 0011 0010
b=a<<3;            // a<<3=    0000 0001 1001 0000    = 400
c=a>>3;             //a>>3=    0000 0000 0000 0110   = 6
printf("%d %d",b,c);

As you can see, we have shifted the bits of  0000 0000 0011 0010(i.e:50) to 3 bits by left and 3 bits by right shift operator. We got the result as 400 & 6 respectively because of the shifted bit positions 0000 0001 1001 0000 for left and 0000 0000 0000 0110 for right.


3. Bitwise One's Complement Operator (~)
: Inverts all the bits represented by it's operands

#include<stdio.h>
int main(){
int a,b,c;
a= 50;                   //50 =   0000 0000 0011 0010
b=~a;                   //~a  =  1111 1111 1100 1101 = -51
printf("%d",b);
return 0;
}

When we invert the bits of decimal 50(i.e. 0000 0000 0011 00) using one's complement operator, we got the output as 1111 1111 1100 1101 = -51 which is clearly shown in the above code.

 Video with detail explanation can be found here : Video Link

 

 P.S: We have used codeblocks IDE to compile these programs. If you have any confusion, queries, feedbacks regarding the video or the post you can reach us at contact.techlover@gmail.com or leave comments on comment section as well.

#staySafe #stayPositive #happyCoding

Thank you.


Share on Google Plus

About Nepali Xoro

Interested in Information Technology, Spreading Knowledge for Nepalease IT Students."Loves Traveling", Listen Music and Surfing web.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment