Linux C一站式学习习题答案16.1.3位运算 掩码

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

#include<stdio.h>

int countbit(unsigned int x)
{
	int i = 0;
	int count = 0;
	int mask = 0x00000001;
	for (i = 0; i < 32; i++) {
		if ( 1 == (x >> i & mask))
			count++;
	}
	return count; 
}

int main()
{
	printf ("%d\n",countbit (0x23));
}


注:转载请注明源地址:http://blog.csdn.net/whorus1/article/list/2,谢谢!
2、用位操作实现无符号整数的乘法运算,函数原型是 unsigned int multiply(unsigned int x, unsigned int y); 。例如:(11011) 2 ×(10010) 2 =((11011) 2 <<1)+((11011) 2 <<4)。

#include<stdio.h>

unsigned int multiply(unsigned int x, unsigned int y)
{
	int i;
	int result = 0;
	int mask = 0x00000001;
	for (i = 0; i < 32; i++) {
			if ( 1 == (x >> i & mask))
				result = result + (y << i);
	}
	return result;
}

int main()
{
	printf ("%d\n",multiply (9, 2));
}


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

#include<stdio.h>

unsigned int rotate_right(unsigned int x, int n)
{
	int i;
	int mask = 1;
	for (i = 1; i < n; i++) {
		mask = ((mask << 1) | 1);
	}
	unsigned int y = (x >> n) | ((x & mask) << (32 - n));
	return y;
}

int main()
{
	printf ("%x\n",rotate_right(0xdeadbeef, 8));
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值