## Friday, July 29, 2016

### C Basics - Bitwise Operators in C

The following table shows all the bitwise operators supported by the C language. Assume variable x holds 21, y holds 10 and variable z holds 0 then.

Operator Name Syntax Description Example
Bitwise AND x & y Binary AND Operator copies a bit to the result if it exists in both operands. z = x & y;
z = 0
Bitwise OR x | y Binary OR Operator copies a bit if it exists in either operand. z = x | y;
z = 31
Bitwise XOR x ^ y Binary XOR Operator copies the bit if it is set in one operand but not both. z = x ^ y;
z = 31
Bitwise NOT ~x Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. z = ~x;
z = -22
Bitwise left shift x << y Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. z = x << 2;
z = 84
Bitwise right shift x >> y Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. z = x >> 2;
z = 5
``````
#include <stdio.h>

int main()
{
int x = 21;
int y = 10;
int z = 0;

printf("Bitwise operators demo\n");
printf("Value of x is %d\n", x );
printf("Value of y is %d\n", y );
printf("Value of z is %d\n", z );

z = x & y;
printf("Bitwise AND (z = x & y): %d\n", z );

z = x | y;
printf("Bitwise OR (z = x | y): %d\n", z );

z = x ^ y;
printf("Bitwise XOR (z = x ^ y): %d\n", z );

z = ~x ;
printf("Bitwise NOT (z = ~x): %d\n", z );

z = x << 2;
printf("Bitwise left shift (z = x << 2): %d\n", z );

z = x >> 2;
printf("Bitwise right shift (z = x >> 2): %d\n", z );
return 0;
}
``````
The output of the above program would be:
``````
Bitwise operators demo
Value of x is 21
Value of y is 10
Value of z is 0
Bitwise AND (z = x & y): 0
Bitwise OR (z = x | y): 31
Bitwise XOR (z = x ^ y): 31
Bitwise NOT (z = ~x): -22
Bitwise left shift (z = x << 2): 84
Bitwise right shift (z = x >> 2): 5
``````

Related topics:
Overview of Operators in C   |   Arithmetic Operators in C   |   Relational Operators in C   |   Logical Operators in C   |   Compound Assignment Operators in C   |   Conditional Operators in C   |   Miscellaneous Operators in C   |   Operator Precedence and Associativity in C

List of topics: C Programming