Bit-wise Operators in C

The bitwise operators are used to perform bit-wise operations on operands or variables. e.g. bit-wise AND operation, bit-wise OR operation, etc.

Bit-wise AND ( & ): The result of bitwise AND is 1 if the corresponding bits of two operands is 1, otherwise the result of corresponding bit evaluated as 0.

Bit-wise OR ( | ): The result of bitwise OR is 1 if at least one corresponding bit of two operands is 1, otherwise the result of the corresponding bit evaluated as 0.

Bit-wise NOT ( ~ ): The result of bit-wise NOT is the one’s complement of the operand. i.e. inverts all bits of the operand.

Bit-wise XOR ( ^ ): The result of bit-wise XOR is 1 if the corresponding bit of two operands is opposite, otherwise the result of the corresponding bit evaluated as 0.

Left Shift ( << ): The value of the left operand is shifted to left by the value specified by the right operand.

Right Shift ( >> ): The value of the left operand is shifted to the right by the value specified by the right operand.

Here is a C program to demonstrate the bit-wise operators

/**  
* To demonstrate use of bitwise operators
*/
#include<stdio.h>
int main ( int argc, char **argv )
{
unsigned char x = 10;
unsigned char y = 12;
printf ( "x = %d, y = %d\n", x, y );
/* Bit-wise AND
* x = 10, ( 00001010 )
* &
* y = 12, ( 00001100 )
* x & y = 8, ( 00001000 )
*/
printf ( "x & y = %d\n", x & y );
/* Bit-wise OR
* x = 10, ( 00001010 )
* |
* y = 12, ( 00001100 )
* x | y = 14, ( 00001110 )
*/
printf ( "x | y = %d\n", x | y );
/* Bit-wise NOT
* x = 10, ( 00001010 )
* ~x = 245, ( 11110101 )
*/
printf ( "~x = %d\n", x = ~x );
/* Bit-wise XOR
* x = 10, ( 00001010 )
* ^
* y = 12, ( 00001100 )
* x ^ y= 6, ( 00000110 )
*/
printf ( "x ^ y = %d\n", x ^ y );
/* Bit-wise left shift
* y = 12, ( 00001100 )
* y << 1 = 24, ( 00011000 )
*/
printf ( "y << 1 = %d\n", y << 1 );
/* Bit-wise right shift
* y = 12, ( 00001100 )
* y >> 1 = 6, ( 00000110 )
*/
printf ( "y >> 1 = %d\n", y >> 1 );
return 0;
}

Hope, it would be useful !!

To contribute :

If you like Advance Computing and would like to contribute, you can  mail your article to “computingadvance@gmail.com”. You will get credit as your name , email id, designation with article on this blog.

Leave a Reply