1.  /* bfs bfr in C
  2.   *
  3.   * Michal 'GiM' Spadlinski http://gim.org.pl/ gim@@at@@skrzynka@@dot@@pl
  4.   *
  5.   * drop me a line, if you've made use of that :-)
  6.   *
  7.   * redistribute under the terms of GPL
  8.   */
  9.  #ifdef __cplusplus
  10.  extern "C" {
  11.  #endif
  12.  
  13.  #define RISC_SUX
  14.  
  15.  #ifdef RISC_SUX
  16.  int bsr (unsigned long int input)
  17.  {
  18.   asm( "bsr %%eax,%%ebx\n"
  19.   "jnz gimskipxorek1\n"
  20.   "xor %%eax, %%eax\n"
  21.   "dec %%eax\n"
  22.   "gimskipxorek1:\n"
  23.   :"=b"(input)
  24.   :"a"(input));
  25.   return input;
  26.  }
  27.  
  28.  int bsf (unsigned long int input)
  29.  {
  30.   asm( "bsf %%eax,%%ebx\n"
  31.   "jnz gimskipxorek2\n"
  32.   "xor %%eax, %%eax\n"
  33.   "dec %%eax\n"
  34.   "gimskipxorek2:\n"
  35.   :"=b"(input)
  36.   :"a"(input));
  37.   return input;
  38.  }
  39.  
  40.  #else
  41.  
  42.  /* these are my implementations for sux0rz risc processors
  43.   * loop unrolled
  44.   */
  45.  int bsr (unsigned long int input)
  46.  {
  47.   long int ret=0,v=input;
  48.   /* step 1 */
  49.   if (v&0xffff0000)
  50.   v>>=16, ret=16;
  51.   v&=0xffff;
  52.   /* step 2 */
  53.   if (v&0xff00)
  54.   v>>=8, ret+=8;
  55.   v&=0xff;
  56.   /* step 3 */
  57.   if (v&0xf0)
  58.   v>>=4, ret+=4;
  59.   v&=0xf;
  60.   /* step 4 */
  61.   if (v&0xc)
  62.   v>>=2, ret+=2;
  63.   v&=0x3;
  64.   if (v&2)
  65.   return ret+1;
  66.   else if (v&1)
  67.   return ret;
  68.   else return 0xff;
  69.  }
  70.  
  71.  int bsf (unsigned long int input)
  72.  {
  73.   long int ret=0,v=input;
  74.   /* step 1 */
  75.   if (!(v&0xffff))
  76.   v>>=16, ret=16;
  77.   v&=0xffff;
  78.   /* step 2 */
  79.   if (!(v&0xff))
  80.   v>>=8, ret+=8;
  81.   v&=0xff;
  82.   /* step 3 */
  83.   if (!(v&0xf))
  84.   v>>=4, ret+=4;
  85.   v&=0xf;
  86.   /* step 4 */
  87.   if (!(v&0x3))
  88.   v>>=2, ret+=2;
  89.   v&=0x3;
  90.   if (v&1)
  91.   return ret;
  92.   else if (v&2)
  93.   return ret+1;
  94.   else return 0xff;
  95.  }
  96.  #endif
  97.  
  98.  #ifdef __cplusplus
  99.  }
  100.  #endif

This document should validate, please check by clicking: Valid XHTML 1.1