位运算习题解答

1、统计一个无符号整数的二进制表示中1的个数,函数原型是int countbit(unsigned int x);

/*Count the number of 1-bits in a positive number.

**By LYLtim

*/

int CountBit(unsigned x)

{

	x = (x & 0x55555555) + ((x >> 1) & 0x55555555);

	x = (x & 0x33333333) + ((x >> 2) & 0x33333333);

	x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F);

	x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF);

	x = (x & 0x0000FFFF) + ((x >> 16) & 0x0000FFFF);

	return x;

}

 巧妙地运用分治思想,详见:http://www.cnblogs.com/LYLtim/archive/2011/11/05/2236816.html

 

2、用位操作实现无符号整数的乘法运算,函数原型是unsigned int multiply(unsigned int x, unsigned int y);。例如:(11011)2×(10010)2=((11011)2<<1)+((11011)2<<4)。

//By LYLtim

unsigned multiply (unsigned x, unsigned y)

{

	unsigned sum = 0, bit = 0;

	while (y != 0) {

		if (y & 1 == 1) sum += x << bit;

		y >>= 1;

		bit += 1;

	}

	return sum;

}

 

3、对一个32位无符号整数做循环右移,函数原型是unsigned int rotate_right(unsigned int x, int n);。所谓循环右移就是把低位移出去的部分再补到高位上去,例如rotate_right(0xdeadbeef, 8)的值应该是0xefdeadbe。

// By LYLtim

unsigned rotate_right(unsigned x, unsigned n)

{

	unsigned tmp = x & ((1 << n) - 1);

	x >>= n;

	x += tmp << (32 - n);

	return x;

}

 

你可能感兴趣的:(位运算)