首页 > 学院 > 开发设计 > 正文

c简单位操作

2019-11-06 07:58:29
字体:
来源:转载
供稿:网友

C语言中位运算符之间,按优先级顺序排列为 1 ~ 2 <<、>> 3 & 4 ^ 5 | 6 &=、^=、|=、<<=、>>=

一、第i位替换

Description:编写程序,使得函数返回值为一个整数,该整数的第i位和m的第i位相同,其他位和n相同。使用bitManipulation1函数。

Input:

第一行是整数 t,表示测试组数。每组测试数据包含一行,是三个整数 n, m 和 i (0<=i<=31)Output:对每组输入数据,每行输出整型变量n变化后的结果Sample Input:
11 2 1Sample Output:
3Tips二进制的最右边是第0位
#include <iostream>using namespace std;int bitManipulation1(int n, int m, int i) {return (n&(~(1<<i)) | ((m >> i)&1)<< i);// ‘n&(~(1<<i)’把n的第i位变为0,其它位不变。//‘(m >> i)&1’把m的各位向右移动i位,第i位跑到0位,作用是取m的第i个bit 。然后各位左移i位,m的第i位不变,其他位为0 }int main() {	int n, m, i, t;	cin >> t;	while (t--) { 		cin >> n >> m >> i;		cout << bitManipulation1(n, m, i) << endl;	}	return 0;}

二:左边i位取反

Description:编写程序,使得函数返回值为一个整数,该整数的左边i位是n的左边i位取反,其余位和n相同。请使用bitManipulation3函数。

Input:第一行是整数 t,表示测试组数。每组测试数据包含一行,是两个整数 n 和 i (1<=i<=32)。Output:对每组输入数据,输出整型变量n中左边i位取反的结果。Sample Input:
10 32Sample Output:
-1Tips注意i从1开始
#include <iostream>using namespace std;int bitManipulation3(int n, int i) {return n ^ (~0<<(32-i));// '~0' 32位字节全部变为1,再右移32-i位,使其左边i位为1,其余为0 }int main() {	int t, n, i;	cin >> t;	while (t--) {		cin >> n >> i;		cout << bitManipulation3(n, i) << endl;	}	return 0;}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表