Thursday, June 14, 2012

Count Leading Zero bits in an integer

How to count all zeros from left to right until reach first set (1) bit? we name it counting leading zeros :
int clz (int x)
{
 if (x ==0)
  return 32;
 int n=0;
 if ((x & 0xFFFF0000) == 0) { n += 16; x =x << 16;} //1111 1111 1111 1111 0000 0000 0000 0000 // 16 bits from left are zero! so we omit 16left bits
 if ((x & 0xFF000000) == 0){ n = n +  8; x = x <<  8;} // 8 left bits are 0
 if ((x & 0xF0000000) ==0){ n = n +  4; x = x <<  4;} // 4 left bits are 0
 if ((x & 0xC0000000) == 0){ n =n +  2, x = x <<  2;}  // 110000....0 2 left bits are zero
 if ((x & 0x80000000) == 0){n = n +  1, x = x <<  1;} // first left bit is zero
 return n;
}

No comments :

Post a Comment

Thursday, June 14, 2012

Count Leading Zero bits in an integer

How to count all zeros from left to right until reach first set (1) bit? we name it counting leading zeros :
int clz (int x)
{
 if (x ==0)
  return 32;
 int n=0;
 if ((x & 0xFFFF0000) == 0) { n += 16; x =x << 16;} //1111 1111 1111 1111 0000 0000 0000 0000 // 16 bits from left are zero! so we omit 16left bits
 if ((x & 0xFF000000) == 0){ n = n +  8; x = x <<  8;} // 8 left bits are 0
 if ((x & 0xF0000000) ==0){ n = n +  4; x = x <<  4;} // 4 left bits are 0
 if ((x & 0xC0000000) == 0){ n =n +  2, x = x <<  2;}  // 110000....0 2 left bits are zero
 if ((x & 0x80000000) == 0){n = n +  1, x = x <<  1;} // first left bit is zero
 return n;
}

No comments :

Post a Comment