- Get the value of nth bit
- Set the value of nth bit
- Clear the value of nth bit
- Toggle the nth bit
- Get the total number of set bits

## 1. Get the value of nth bit

To get the value of nth bit, you have to do a right shift “n” times and perform bitwise AND with 1.

nBit = (num >> n) & 1;

## 2. Set the value of nth bit

To set a value we use bitwise OR operator. To set the nth bit, we left shift 1, n times and do a bitwise OR with the given number.

(1 << n) | num

## 3. Clear the value of nth bit

To clear the value of nth bit, we perform below operations:

1. Left shift 1 , n times i.e 1 << n

2. Perform bitwise complement of the above result, so that the nth bit will become unset and rest will become set.

3. Perform bitwise AND with the above result with the num.

The above 3 steps can be written as:

num & (~(1 <<n))

## 4. Toggle the nth bit

To toggle nth bit we perform below steps:

1. Left shift 1, n times.

2. Perform XOR with the above result and with the number. i.e num ^ (1 << n)

## 5. Get the total number of set bits

To get the total number of bits, right shift by one, till the element is null.

## Solution in C++

/* * File : bitwise_operations.cpp * Author : ajay.thousand@gmail.com * Copyright: @ prodevelopertutorial.com */ #include<iostream> #include<vector> #include<string> using namespace std; void get_n_bit_value(int num, int n) { int bitStatus = (num >> 1)&1; cout<<"The "<< n <<"th bit value is "<< ((num >> 1)&1)<<endl; } void set_n_bit_value(int num, int n) { cout<<"The number before setting is = "<< num <<endl; cout<<"The number after setting "<<n<<" th bit is = "<< ((1 << n)|num) <<endl; } void clear_n_bit_value(int num, int n) { cout<<"The number before clearning is = "<< num <<endl; cout<<"The number after clearning "<<n<<" th bit is = "<< (num & (~(1 <<n)))<<endl; } void toggle_n_bit_value(int num, int n) { cout<<"The number before toggling is = "<< num <<endl; cout<<"The number after toggling "<<n<<" th bit is = "<< (num ^ (1 << n))<<endl; } void get_total_bit_number(int num) { int count = 0; int temp = num; while (num) { count++; num >>= 1; } cout<<"The total number of bits in the num = "<<temp<<" is = " <<count<<endl; } int main() { int num =12; int n = 2; get_n_bit_value(num, n); set_n_bit_value(num, n); clear_n_bit_value(num, n); toggle_n_bit_value(num, n); get_total_bit_number(num); return 0; }

## Output:

The 2th bit value is 0 The number before setting is = 12 The number after setting 2 th bit is = 12 The number before clearning is = 12 The number after clearning 2 th bit is = 8 The number before toggling is = 12 The number after toggling 2 th bit is = 8 The total number of bits in the num = 12 is = 4