求取32位无符号整数中最低位位值为1的位置 && 求取32位无符号整数中最高位位值为1的位置

      3 int bit_pos(unsigned int n)
      4 {
      5     n = n & (-n);                                                                                           
      6     n = n - 1;
      7     n = n - ((n>>1)&0x77777777) - ((n>>2)&0x33333333)-((n>>3)&0x11111111);
      8     n = (n + (n>>4))&0xf0f0f0f;
      9     n = n + ((n >> 8)& 0xf) + ((n >> 16)& 0xf) + ((n >> 24)& 0xf);
     10     n = n & 0xff;
     11     return n;
     12 }


注:输入为0时返回值位32

static inline int ffs(int x)
{
     int r = 1;
     if (!x)
         return 0;
     if (!(x & 0xffff)) {
          x >>= 16;
          r += 16;
     }

     if (!(x & 0xff)) {
         x >>= 8;
         r += 8;
    }

     if(!(x & 0xf)) {
          x >>= 4;
          r += 4;
     }

     if(!(x & 3)) {
          x >> = 2;
         r += 2;
    }
    
    if(!(x & 1)) {
         x >>= 1;   
         r += 1;
    }
   
    return r;
}

 

uint lowest_one_idx(uint x)

{

  uint r = 0;

  x &= ~x;

  if(x & 0xffff0000)

    r += 16;

  if(x & 0xff00ff00)

    r += 8;

  if(x & 0xf0f0f0f0)

    r += 4;

  if(x &0xcccccccc)

    r += 2;

  if(x & 0xaaaaaaaa)

    r += 1;

  return r;

}

posted on 2012-09-18 12:04  阿加  阅读(1135)  评论(0编辑  收藏  举报

导航