关于位操作符的小练习

  1. 写一个函数返回参数二进制中 1 的个数。
    比如: 15 0000 1111 4 个 1
    程序原型:
    int count_one_bits(unsigned int value)
    {
    // 返回 1的位数
    }

这里主要利用位操作符的作用

#include <stdio.h>
#include <stdlib.h>
int count_one_bits(unsigned int num) {
	int i = 0;
	int count = 0;
	for(i=0;i<32;++i) {
		if((num>>1)&1==1) {
			count++;
		}
	}
	return count;
}
int main() {
	int num = 0;
	printf("请输入一个数:");
	scanf("%d",&num);
	printf("二进制中1的个数=%d\n",count_one_bits(num));
	system("pause");
	return 0;
}
#include <stdio.h>
#include <stdlib.h>
int count_one_bits(unsigned int num) {
	int count = 0;
	while(num) {
		count ++;
		num = num & (num-1)   //每运算一次消一个bit
	}
	return count;
}
int main() {
	int num = 0;
	printf("请输入一个数:");
	scanf("%d",&num);
	printf("二进制中1的个数=%d\n",count_one_bits(num));
	system("pause");
	return 0;
}
  1. 获取一个数二进制序列中所有的偶数位和奇数位, 分别输出二进制序列。
#include <stdio.h>
#include <stdlib.h>
void Sort_Odd_Even(unsigned int num) {
	int i = 0;
	int ret1 = 0;
	int ret2 = 0;
	printf("奇数位为:");
		for(i=31;i>=0;i-=2) {
			ret1 = (num>>i) & 1;
			printf("%d",ret1);
		}
	printf("\n");
	printf("偶数位为:");
		for(i=30;i>=0;i-=2) {
			ret2 = (num>>i) & 1;
			printf("%d",ret2);
		}
	printf("\n");
}
int main() {
	int num = 0;
	printf("请输入一个数:");
	scanf("%d",&num);
	Sort_Odd_Even(num);
	system("pause");
	return 0;
}
  1. 输出一个整数的每一位。
#include <stdio.h>
#include <stdlib.h>
void Output_one_bits(unsigned int num) {
	int i = 0;
	int ret = 0;
	for(i=31;i>=0;--i) {
		ret = (num>>i) & 1;
		printf("%d",ret);
	}
}
int main() {
	int num = 0;
	printf("请输入一个数:");
	scanf("%d",&num);
	Output_one_bits(num);
	system("pause");
	return 0;
}
  1. 编程实现:
    两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同?
    输入例子:
    1999 2299
    输出例子:7
#include <stdio.h>
#include <stdlib.h>
int Count_bits_num(unsigned int num1,unsigned int num2) {
	int i = 0;
	int count = 0;
	for(i=31;i>=0;--i) {
		int ret1 = 0;
		int ret2 = 0;
		ret1 = (num1 >> i) & 1;
		ret2 = (num2 >> i) & 1;
		if((ret1^ret2)==1) {
			count++;
		}
	}
	return count;
}
int main() {
	int num1 = 0;
	int num2 = 0;
	printf("Please input two numbers:");
	scanf("%d %d",&num1,&num2);
	printf("The different bits = %d\n",Count_bits_num(num1,num2);
	system("pause");
	return 0;
}
上一篇:DGUT-Cnam Courses: Computer System Design & Analysis – Java Programming


下一篇:Redis缓存穿透