The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

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;
}

Back | Next

All problems on Bit Manipulation
* Count the number of set bits in an integer
* Find out whether a bit in a particular position in the binary representation of an unsigned integer is set or not
* Check if a number is a power of 2 using bit operation.
* Add two numbers without using any arithmetic operator
* Find the number of bits which are to be flipped to convert one integer to another
* Reverse the bits of an unsigned integer