Home →C Programming Language →C Operators
Bitwise Operators
#include <stdio.h>
/* a demonstration of C bitwise operators */
void main()
{
int d1 = 4,/* 101 */
d2 = 6,/* 110*/
d3;
printf("\nd1=%d",d1);
printf("\nd2=%d",d2);
d3 = d1 & d2; /* 0101 & 0110 = 0100 (=4) */
printf("\n Bitwise AND d1 & d2 = %d",d3);
d3 = d1 | d2;/* 0101 | 0110 = 0110 (=6) */
printf("\n Bitwise OR d1 | d2 = %d",d3);
d3 = d1 ^ d2;/* 0101 & 0110 = 0010 (=2) */
printf("\n Bitwise XOR d1 ^ d2 = %d",d3);
d3 = ~d1; /* ones complement of 0000 0101 is 1111 1010 (-5) */
printf("\n Ones complement of d1 = %d",d3);
d3 = d1<<2;/* 0000 0101 left shift by 2 bits is 0001 0000 */
printf("\n Left shift by 2 bits d1 << 2 = %d",d3);
d3 = d1>>2;/* 0000 0101 right shift by 2 bits is 0000 0001 */
printf("\n Right shift by 2 bits d1 >> 2 = %d",d3);
}
And here is the output
d1=4 d2=6 Bitwise AND d1 & d2 = 4 Bitwise OR d1 | d2 = 6 Bitwise XOR d1 ^ d2 = 2 Ones complement of d1 = -5 Left shift by 2 bits d1 << 2 = 16 Right shift by 2 bits d1 >> 2 = 1
