Wednesday, 1 April 2015

Setting and clearing the bit in C++:



Setting and clearing the bit in C++:

#include <iostream>

using namespace std;

bool GetBitVal(int Num, int iIndex)
{
 return ( (Num & (1 << iIndex) ) > 0);
}

int SetBitVal(int Num, int iIndex, bool b)
{
 if(b)
  return (Num | (1 << iIndex)) ; 
 else {
  int mask = ~(1 << iIndex);
  return Num & mask;
 }
}

int main ()
{
 int iNumber = 0, iIndex = 0;

 iNumber = 20;

 cout << "Input" << endl;
 for (int iInd = 7; iInd >= 0; iInd--) 
  cout << GetBitVal(iNumber,iInd) << " ";
 cout << endl;

 /* set bit */
 iIndex = 4;
 cout << "Setting " << iIndex << "-th bit" << endl;
 iNumber = SetBitVal(iNumber, iIndex, true);
 for (int iInd = 7; iInd >= 0; iInd--) 
  cout << GetBitVal(iNumber,iInd) << " ";
 cout << endl;

 /* unset (clear) bit */
 iIndex = 5;
 cout << "Unsetting (Clearing) " << iIndex << "-th bit" << endl;
 iNumber = SetBitVal(iNumber, iIndex, false);
 for (int iInd = 7; iInd >= 0; iInd--) 
  cout << GetBitVal(iNumber,iInd) << " ";
 cout << endl;
  getchar ();

 return 0;
}
Output of the above program is:
Input
0 0 0 1 0 1 0 0
Setting 4-th bit
0 0 0 1 0 1 0 0
Unsetting (Clearing) 5-th bit
0 0 0 1 0 1 0 0

No comments: