C回顾4之位的应用

1.写一个函数返回参数二进制中 1 的个数

#include
#include
#pragma warning(disable:4996)
int  count_one_bits(unsigned int value)
{
	int count = 0;
	for (int i = 0; i < 32; i++)
	{
		if ((value & 1) == 1)
		{
			count++;
		}
		value = value >> 1;
	}
	return count;
}
int main()
{
	unsigned int value = 0;
	scanf("%d", &value);
	int ret = count_one_bits(value);
	printf("%d\n", ret);
	system("pause");
	return 0;
}

2.获取一个数二进制序列中所有的偶数位和奇数位,分别输出二进制序列。

#include     
#include
#pragma warning(disable:4996)
int main()
{
	int date = 0;
	printf("请输入数字:");
	scanf("%d", &date);
	int a[32];
	int i = 0;
	for (i = 0; i < 32; i++)
	{
		a[i] = date % 2;
		date /= 2;
	}
	printf("偶数:");
	for (i = 31; i >= 0; i -= 2)
	{
		printf("%d", a[i]);
	}
	printf("\n");
	printf("奇数:");
	for (i = 30; i >= 0; i -= 2)
	{
		printf("%d", a[i]);
	}
	printf("\n");
	system("pause");
	return 0;
}

3.编程实现: 
两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同?

#pragma warning(disable:4996)
#include
#include
int main()
{
	int i = 0;
	int m = 0;
	int n = 0;
	int count = 0;
	printf("请输入两个数:\n");
	scanf("%d%d", &m, &n);
	for (i = 0; i < 32; i++)
	{
		if ((m & 1) != (n & 1))
		{
			count++;
		}
		m = m >> 1;
		n = n >> 1;
	}
	printf("count=%d", count);
	system("pause");
	return 0;
}

 

你可能感兴趣的:(C回顾4之位的应用)