Bit Manipulation

Problem
Find out whether a bit in a particular position in the binary representation of an unsigned integer is set or not.

Solution
Suppose we need to find whether bit in ‘i’th position is set or not.
This can be done by an AND operation of the given unsigned integer with 2i because 2i would result into a number in which only the bit in ith position is set.

#include<iostream>
#include<cmath>
using namespace std;

// check if a bit in a particular position in the
// binary representation of an unsigned integer is set or not
// Logic :- To check whether 'i'th bit is set or not, we can do
// a bitwise 'AND' operation of the no. with 2^i
bool isBitSet(unsigned int num,unsigned int pos) {
unsigned int k = pow(2,pos);
return (num & k);
}

// main
int main() {
unsigned int num = 37;
unsigned int bit_pos = 5;
bool bit_set = isBitSet(num,bit_pos);
if (bit_set)
cout<<"\nBit Pos "<<bit_pos<<" in "<<num<<" is set";
else
cout<<"\nBit Pos "<<bit_pos<<" in "<<num<<" is not set";
cout<<endl;
return 0;
}