#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;
}
本文详细介绍了如何通过位运算实现获取整数中左、右第一个1的位数的算法,并提供了具体的代码实现。
731

被折叠的 条评论
为什么被折叠?



