Monday, April 18, 2011

Note: Setbit

#include <iostream>
using namespace std;
char* getBitPattern(unsigned int val, int fromIndex, int toIndex){
  char* bp= new char[toIndex - fromIndex + 2];
  int i, j;
  for(i=toIndex,j=0;i>=fromIndex;i--,j++){
    // slow
    //if((1 << i) & val){
    //  bp[j] = '1';
    //}
    //else{
    //  bp[j] = '0';
    //}
    //fast
    //bp[j] = ((1 << i) & val) ? '1':'0';
    // faster
    bp[j] = !!((1 << i) & val) + '0';

  }
  bp[j] = 0;
  return bp;
}
int main(){
  unsigned int v = 0x0000FF00;
  char* bits = getBitPattern(v, 4, 11);
  cout<<bits<<endl;
  delete[] bits;
  return 0;
}

The rerult of his problem is 11110000.

No comments:

Post a Comment