Get to know Bitwise Operators - C Operator

C examples for Operator:Bit Operator

Introduction

Bitwise operation can test, set, or shift the bits in char and int data types.

You cannot use bitwise operations on float, double, long double, void.

Operator Action
& AND
| OR
^ Exclusive OR (XOR)
~ One's complement (NOT)
>>Shift right
<<Shift left

The bitwise AND, OR, and NOT are governed by the same truth table as their logical equivalents, except that they work bit by bit.

The exclusive OR has the truth table shown here:

p qp ^q
0 0 0
1 0 1
1 1 0
0 1 1

The outcome of an XOR is true only if exactly one of the operands is true; otherwise, it is false.

The bitwise shift operators can also quickly multiply and divide integers.

A shift right effectively divides a number by 2 and a shift left multiplies it by 2.

The following program illustrates the shift operators:

Demo Code

#include <stdio.h>

int main(void)
{
   unsigned int i;
   int j;/* w  ww  . j  a v a2 s  .co  m*/

   i = 1;

   /* left shifts */
   for (j = 0; j<4; j++) {
      i = i << 1; /* left shift i by 1, which
                  is same as a multiply by 2 */
      printf("Left shift %d: %d\n", j, i);
   }

   /* right shifts */
   for (j = 0; j<4; j++) {
      i = i >> 1; /* right shift i by 1, which
                  is same as a division by 2 */
      printf("Right shift %d: %d\n", j, i);
   }

   return 0;
}

Result

The NOT bit operator, ~, reverses the state of each bit in its operand. That is, all 1's are set to 0, and all 0's are set to 1.

unsigned char x;binary value of x
x = 7; 00000111 7
x = x<<l; 0000111014
x = x<<3; 01110000112
x = x<<2; 11000000192
x = x>>l; 0110000096
x = x>>2; 0001100024

Each left shift multiplies by 2.

Notice that information has been lost after x<<2 because a bit was shifted off the end.


Related Tutorials