Bitwise operations in C

Introduction

Bitwise AND


int x = 12;
int y = 10;

z = x & y;

int x = 12;
int y = 10;

// Following two lines are equivalent.
x &= y;
x = x & y;

Bitwise OR


int x = 12;
int y = 10;

z = x | y;

int x = 12;
int y = 10;

// Following two lines are equivalent.
x |= y;
x = x | y;

Bitwise NOT


int x = 12;

int y =  ~x;

Bitwise XOR


int x = 12;
int y = 10;

z = x ^ y;

int x = 12;
int y = 10;

// Following two lines are equivalent.
x ^= y;
x = x ^ y;

Left bitshifts

Left shift shifts all bits to the left. In binary, left shift by 1 place is same as multiplying by 2, assuming no overflows.

We can left shift by any number of places.

The new bit on the furthest right is set to 0.


int x = 12;
int y = 2;

int z = x << y;

int x = 12;
int y = 2;

// Following two lines are equivalent.
x <<= y;
x = x << y;

Right bitshifts

Right shift shifts all bits to the right. In binary, right shift by 1 place is same as diving by 2 and dropping the remainder.

We can right shift by any number of places.

The new bit on the furthest left is set to 0.


int x = 12;
int y = 2;

int z = x >> y;

int x = 12;
int y = 2;

// Following two lines are equivalent.
x >>= y;
x = x >> y;