What are Bitwise Operators - C Operator

C examples for Operator:Bit Operator

Introduction

The bitwise operators can manipulate individual bits inside an integer.

The bitwise left shift operator << moves all bits to the left with the specified number of steps.

Demo Code

#include <stdio.h>
int main(void) {
    int x = 5 & 4;  /* 101 & 100 =  100 (4) - and */
        x = 5 | 4;  /* 101 | 100 =  101 (5) - or */
        x = 5 ^ 4;  /* 101 ^ 100 =  001 (1) - xor */
        x = 4 << 1; /* 100 << 1  = 1000 (8) - left shift */
        x = 4 >> 1; /* 100 >> 1  =   10 (2) - right shift */
        x = ~4;     /* ~00000100 = 11111011 (-5) - invert */
}

The bitwise operators also have combined assignment operators.

Demo Code

#include <stdio.h>
int main(void) {
   int x = 5; x &= 4; /* 101 & 100 =  100 (4) - and */
   x = 5; x |= 4; /* 101 | 100 =  101 (5) - or */
   x = 5; x ^= 4; /* 101 ^ 100 =  001 (1) - xor */
   x = 4; x <<= 1; /* 100 << 1  = 1000 (8) - left shift */
   x = 4; x >>= 1; /* 100 >> 1  =   10 (2) - right shift */
}

Related Tutorials