反转一个字节 和 判断32位整数二进制中1的个数 的算法

http://blog.csdn.net/todototry/article/details/1575900

unsigned char reverse8( unsigned char c )

{
c = ( c & 0×55 ) << 1 | ( c & 0xAA ) >> 1;
c = ( c & 0×33 ) << 2 | ( c & 0xCC ) >> 2;
c = ( c & 0x0F ) << 4 | ( c & 0xF0 ) >> 4;
return c;
}

unsigned long func(unsigned long x)
{
x = (x & 0x55555555UL) + ((x >> 1) & 0x55555555UL);
x = (x & 0x33333333UL) + ((x >> 2) & 0x33333333UL);
x = (x & 0x0f0f0f0fUL) + ((x >> 4) & 0x0f0f0f0fUL);
x = (x & 0x00ff00ffUL) + ((x >> 8) & 0x00ff00ffUL);
x = (x & 0x0000ffffUL) + ((x >> 16) & 0x0000ffffUL);
return x;

}

比这个慢的。按照传统的思维,按位左移。

unsigned char shift(unsigned char n)

{

unsigned char ans=0×00;

for(int i=1;i<=8;i++,n=n>>1)

{

unsigned char t=n&0×01;

ans+=t<<(8-i);

}

return ans;

}

简化后可以变为

unsigned char reverse_bit(unsigned char n)

{

for(unsigned char ans=0×0,int i=1;i<=8;ans+=(n&0×01)<<(8-i++),n=n>>1);

return ans;

}

 

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>