Bitwise Operators in C

In this tutorial, you will learn about the Bitwise Operations in C and their usage and examples.

Bitwise Operations in C with Example

The table below illustrates the Bitwise Operators in C, a brief description, and a simple example.

OperatorDescriptionExample
&"AND" Operator copies a bit to the result if it exists in both operands.(A & B)
|"OR" Operator copies a bit if it exists in either operand.(A | B)
^"XOR" Operator copies the bit if it is set in one operand but not both.(A ^ B)
~One's Complement Operator is unary and has the effect of 'flipping' bits.(~A )
<<Left Shift Operator. The left operand's value is moved left by the number of bits specified by the right operand.A << 2
>>Right Shift Operator. The left operand's value is moved right by the number of bits specified by the right operand.A >> 2

Example of Bitwise Operators in C

#include <stdio.h>

int main()
{
   int x = 20,y = 40,AND_Operation,OR_Operation,XOR_Operation,NOT_Operation ;
   AND_Operation = (x&y);
   OR_Operation = (x|y);
   NOT_Operation = (~x);
   XOR_Operation = (x^y);
   printf("AND_Operation value = %d\n",AND_Operation );
   printf("OR_Operation value = %d\n",OR_Operation );
   printf("NOT_Operation value = %d\n",NOT_Operation );
   printf("XOR_Operation value = %d\n",XOR_Operation );
   printf("Left_Shift value = %d\n", x << 1);
   printf("Right_Shift value = %d\n", x >> 1);
}

Output

AND_Operation value = 0
OR_Operation value = 60
NOT_Operation value = -21
XOR_Operation value = 60
Left_Shift value = 40
Right_Shift value = 10

 

Back to: Learn C Programming > Expression and Operators in C

Leave a Reply

Your email address will not be published. Required fields are marked *