,  

Find the nth bit of a number

Problem: Given a numbers n and k. Write a program to print the value of kth bit in the binary representation of the number.

For example:
Input: n = 10
       k = 2
Output: 1
The binary representation of 10: (1010)
2nd bit is 1.
Method 1: To get the nth bit of any number we just need to right shift the number n times and then perform bitwise AND operation with the shifted number and 1. In general you may say (number >> n) & 1.
  • 0 & 1 = 0 
  • 1 & 0 = 0 
  • 1 & 1 = 1
#include <bits/stdc++.h>
using namespace std;

/* driver function*/
int main() 
{
    int n = 10;
    int k = 2;

    /* we did k - 1 because, the bit position starts from 0 */
    cout<<((10 >> (k - 1)) & 1)<<"\n";
    
    return 0;
}
Output:
1