获得32位数二进制位的第一个1的位置

本文详细介绍了如何通过位运算实现获取整数中左、右第一个1的位数的算法,并提供了具体的代码实现。


#include <stdio.h>
#include <stdlib.h>


int GetLeftFirstone(unsigned int v)
{
    v ^= v - 1;
    v = (v & 0x55555555) + ((v >> 1) & 0x55555555);
    v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
    v = (v + (v >> 4)) & 0x0F0F0F0F;
    v += v >> 8;
    v += v >> 16;

    return (v & 0x3F) - 1;
}


int GetLeftFirstOne(unsigned int v)
{
 int pos=0;

 if (!(v & 0xFFFF))
 { 
  v >>= 16;
  pos += 16;
 }
 if (!(v & 0xFF))
 {
  v >>= 8;
  pos += 8;
 }
 if (!(v & 0xF))
 {
  v >>= 4;
  pos += 4;
 }
 if (!(v & 0x3))
 {
  v >>= 2;
  pos += 2;
 }
 if (!(v & 0x1))
    {
  pos += 1;
    }

 return pos;
}


int GetRightFirstOne(unsigned int v)
{
 int pos=0;

 if (!(v & 0xFFFF0000))
 { 
  v <<= 16;
  pos += 16;
 }
 if (!(v & 0xFF000000))
 {
  v <<= 8;
  pos += 8;
 }
 if (!(v & 0xF0000000))
 {
  v <<= 4;
  pos += 4;
 }
 if (!(v & 0xC0000000))
 {
  v <<= 2;
  pos += 2;
 }
 if (!(v & 0x80000000))
    {
  pos += 1;
    }

 return pos;
}


int main(void)
{
    char buf[64];
    unsigned int m, n = 0xbc803600;
    printf("n = %d (%X %s)\n", n, n, itoa(n, buf, 2));

    m = GetLeftFirstone(n);
    printf("m = %d\n", m);

    system("pause");

    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值