:: [intv] Bit manipulations. ::
HOME


[Date Prev][Date Next][Date Index]

[intv] Bit manipulations.


//Problem: Bit Manipulations.
//Save as: main.cpp and compile as: g++ -o main main.cpp

#include <iostream>
#include <iomanip>
#include <bitset>
using namespace std;

int Ones(int);
int reverseBits(int);


int main(){ int a = 0xabcd; cout << "Number of 1's in " << setbase(16) << a << " = " << Ones(a) << endl; cout << "Bit Reverse " << setbase(16) << a << " = " << reverseBits(a) << endl; cout << "Binary " << bitset<32>(a) <<endl;


}


int Ones(int a){ int count = 0; if (a == 0) {return 0;}

  while((a=a&a-1)) count++;
  return ++count;

}

int reverseBits(int a){
  int tmp = a;

  tmp = ((tmp & 0xffff0000) >> 16) | ((tmp & 0x0000ffff) << 16);
  tmp = ((tmp & 0xff00ff00) >> 8) | ((tmp & 0x00ff00ff) << 8);
  tmp = ((tmp & 0xf0f0f0f0) >> 4) | ((tmp & 0x0f0f0f0f) << 4);
  tmp = ((tmp & 0xcccccccc) >> 2) | ((tmp & 0x33333333) << 2);
  tmp = ((tmp & 0xaaaaaaaa) >> 1) | ((tmp & 0x55555555) << 1);
  return tmp;

}


Comments and corrections are appreciated and can be sent to papers@mia.ece.uic.edu. Click here for ©opyright information.