Write a program to extact a ith bit from a 64-bit integer.

Logic:
A 64-bit integer can be viewed as an array of 64 bits,  with the bit at index 0 corresponding to the least significant bit and the bit at index 63 corresponding to the most significant bit.
To extract ith of an integer, you have to simply right shift to number with i times and apply and (&) bitwise operator with 1, if true then  ith bit was 1 otherwise 0.

Program:

 

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char** argv) {
    int a = 8;  // Original number 
    int i = 2 ; // ith bit 
    int x = a >> i ;  // right sift of a number ith times. 
    if (x & 1 ) {  // comparing  with 1 
        cout << "1 ";
    }else { 
        cout << " 0 " ;
    }
    return 0;
}
Author: Hrishikesh Mishra