You are here

Bitwise operators in C

Bitwise operators in C programming language: In this tutorial I am going to discuss bitwise operators with example C programs. As you know data is stored in memory in the form of bits and a bit is the unit of memory which can be either zero (0) or one (1). We will perform operations on individual bits.

C programming code

  1. #include <stdio.h>
  2.  
  3. main()
  4. {
  5.    int x = 7, y = 9, and, or, xor, right_shift, left_shift;
  6.    
  7.    and = x & y;
  8.    or  = x | y;
  9.    xor = x ^ y;
  10.    left_shift = x << 1;
  11.    right_shift = y >> 1;
  12.    
  13.    printf("%d AND %d = %d\n", x, y, and);
  14.    printf("%d OR  %d = %d\n", x, y, or);
  15.    printf("%d XOR %d = %d\n", x, y, xor);
  16.    printf("Left shifting %d by 1 bit = %d\n", x, left_shift);
  17.    printf("Right shifting %d by 1 bit = %d\n", y, right_shift);
  18.    
  19.    return 0;
  20. }

Left shift operator example program

  1. #include <stdio.h>
  2.  
  3. main()
  4. {
  5.    int n = 1, c, power;
  6.    
  7.    for ( c = 1 ; c <= 10 ; c++ )
  8.    {  
  9.       power = n << c;
  10.       printf("2 raise to the power %d = %d\n", c, power);
  11.    }
  12.  
  13.    return 0;
  14. }