Friday, March 18, 2011

Setting a Bit Pattern

Here's some code that will set the bits of a variable to a specified pattern.  It does not require any external libraries to be used.

void SetBitPattern(unsigned int& V, const char* pattern, int startBitIndex){
  int len;
  for(len = 0 ; pattern[len] ; len++);
  for(len = (startBitIndex + len - 1) ; 
    *pattern ;
    V = (*pattern - '0' ? (V | (1<<len)) : (V & ~(1<<len))), pattern++ , len--);
}