Return index of highest bit set - CSharp System

CSharp examples for System:Bit

Description

Return index of highest bit set

Demo Code


using System;//ww w  .  j a  va2  s . c o m

public class Main{
    // Return index of highest bit set.
      // Return 0 if no bit is set.
      public static int HighestBitIdx( UInt32 x )
      {
         if( 0 == x )
            return  0;

         //    // this version avoids all if() statements:
         //    x = ( highest_bit(x) << 1 ) - 1;
         //    return  bit_count_01(x) - 1;

         int r = 0;

         if( ( x & 0xffff0000 ) != 0 ) { x >>= 16;  r += 16; }
         if( ( x & 0x0000ff00 ) != 0 ) { x >>=  8;  r +=  8; }
         if( ( x & 0x000000f0 ) != 0 ) { x >>=  4;  r +=  4; }
         if( ( x & 0x0000000c ) != 0 ) { x >>=  2;  r +=  2; }
         if( ( x & 0x00000002 ) != 0 ) {            r +=  1; }

         return r;
      }
}

Related Tutorials