Get Nth bit in C++

Written by

Garvit Gulati

Given a number num and a value n, we have to find the value of nth bit from right in the binary representation of that number.

Introduction to Left shift and Right shift operator

  • The left shift and right shift operators are used to shift the bits of a number either left or right as specified.
  • RIGHT SHIFT(>>): it accepts to numbers, and shifts the first number to the right, number of times as specified by the second number. For example,

Ex-1. 13>>2 = 3

Explanation:

Binary equivalent of 13 – 1101

Shifting it to the right two times gives 11 which is binary equivalent of 3.

  • Shifting a number to right n times, is equivalent to dividing the number by 2n.
  • LEFT SHIFT(>>): it accepts to numbers, and shifts the first number to the left, number of times as specified by the second number. For example,

Ex-2. 13<<2 =52

Explanation:

Binary equivalent of 13 – 1101

Shifting it to the left two times gives 110100 which is binary equivalent of 52.

Shifting a number to left n times, is equivalent to multiplying the number by 2n.

# Approaching the problem

  1. To access the nth bit from right, we can keep dividing the number by 2, n times and then the remainder is our answer. But this approach is lengthy as we would have to write while loop.
  2. Instead we can solve this in one step, we would shift the bits of the number by n-1, so that the bit we wish to obtain is now the last bit of the number. Now we will make all the bits of the number 0 except the last bit (it will retain its value) by taking bitwise and with 1.

# Algorithm

  1. Input the values of num and n.
  2. Shift num to right n-1 times.
  3. Take bitwise and with 1 and the result is our answer.

Code

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main()

{ int num, n;

cout &lt;&lt; "Enter number\n";

cin &gt;&gt; num;

cout &lt;&lt; "Enter bit number you wish to obtain\n";

cin &gt;&gt; n;

cout &lt;&lt; "Answer:" &lt;&lt; (1 &amp;(num &gt;&gt; (n - 1)));

}

Output:

Enter Number 
2345

Enter bit number you wish to obtain 6

Answer:1

Binary equivalent of 2345: 100100101001

Get Nth bit in C++