Return index of lowest bit set - CSharp System

CSharp examples for System:Bit

Description

Return index of lowest bit set

Demo Code


using System;// w w  w .  ja  v a 2 s  .  co  m

public class Main{
    // Return index of lowest bit set.
      // Bit index ranges from zero to BITS_PER_LONG-1.
      // Examples:
      //    ***1 --> 0
      //    **10 --> 1
      //    *100 --> 2
      // Return 0 (also) if no bit is set.
      public static int LowestBitIdx( UInt32 x )
      {
         //    if ( 1>=x )  return  x-1; // 0 if 1, ~0 if 0
         //    if ( 0==x )  return  0;

         int r = 0;
         
         x &= (UInt32)(-x);  // isolate lowest bit
         
         if( ( x & 0xffff0000 ) != 0 )  r += 16;
         if( ( x & 0xff00ff00 ) != 0 )  r += 8;
         if( ( x & 0xf0f0f0f0 ) != 0 )  r += 4;
         if( ( x & 0xcccccccc ) != 0 )  r += 2;
         if( ( x & 0xaaaaaaaa ) != 0 )  r += 1;

         return r;
      }
}

Related Tutorials