# Bitwise Operators and their working with Examples in C

**Bitwise operations in C and their working**: Here, we are going to learn **how bitwise operator work in C programming language**?

Submitted by Radib Kar, on December 21, 2018

### 1) & (bitwise AND)

It does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.

**Example:**

4 & 7 4 → 00000100 7 → 00000111 Doing AND for each bit From LSB: 0 & 1= 0 (LSB of output) 0 & 1= 0 1 & 1= 1 0 & 0 =0 0 & 0 =0 0 & 0 =0 0 & 0 =0 0 & 0 =0 Thus output: 00000100 → 4 4 & 7 =4

### 2) | (bitwise OR)

It takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.

**Example:**

4 | 7 4 → 00000100 7 → 00000111 Doing OR for each bit From LSB: 0 | 1 =1 (LSB of output) 0 | 1 =1 1 | 1 =1 0 | 0 =0 0 | 0 =0 0 | 0 =0 0 | 0 =0 0 | 0 =0 Thus output: 00000111 → 7 4 | 7 =7

### 3) ^ (bitwise XOR)

It does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.

**Example:**

4 ^ 7 4 → 00000100 7 → 00000111 Doing XOR for each bit From LSB: 0 ^ 1 =1 (LSB of output) 0 ^ 1 =1 1 ^ 1 =0 0 ^ 0 =0 0 ^ 0 =0 0 ^ 0 =0 0 ^ 0 =0 0 ^ 0 =0 Thus output: 00000011 → 3 4 ^ 7 =3

### 4) << (left shift)

It takes two operands, left shifts the bits of the first operand, the second operand decides the number of places to shift. In every left shift all bits are shifted to left adding a logical 0 at LSB.

**Example:**

4<<1 Before 1 left shift 00000100 After 1 left shift 00001000 → 8 So 4<<1 = 8

### 5) >> (right shift)

It takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.

4>>1 Before 1 right shift 00000100 After 1 right shift 00000010 → 2 So 4<<1 = 2

### 6) ~ (bitwise NOT)

It takes one operand and inverts all bits of it

**Example:**

~4 00000100 → 11111011 ~4=251

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.