打开关闭位的操作

xiaoxiao2021-03-01  7

#include <stdio.h> #include<math.h> /* 当flag为1时把第n位的0变为1 */ /* 当flag为0时把第n位的1变为0 */ /* 假设n从右侧开始,最右边第一位是1 */ void setBit(unsigned* pData, unsigned n, unsigned flag){ unsigned m; if(flag == 0){ m = pow(2, 32) - 1 - pow(2, n - 1); *pData &= m; } else{ m = pow(2, n - 1);//m = 4即0100 *pData |= m;//1010 | 0100 = 1110 } } int main(){ unsigned data = 10;//1010 unsigned n = 2;//把第二位1变为0,输出8 //unsigned n = 3;//把第三位0变为1,输出14 unsigned flag = 0;//flag为0把1变为0 //unsigned flag = 1;//flag为1,把0变为1 setBit(&data, 2, 0); printf("%d\n", data); return 0; }

第二版:更简单 

#include <stdio.h> #include<math.h> #include<iostream> using namespace std; /* 当flag为1时把第n位的0变为1 */ /* 当flag为0时把第n位的1变为0 */ /* 假设n从右侧开始,最右边第一位是1 */ void setBit(unsigned* pData, unsigned n, unsigned flag){ unsigned m = 0x1; if(flag == 0){ m = m<<(n - 1); m = ~m; *pData &= m; } else{ m = m<<(n - 1); *pData |= m; } } int main(){ unsigned data = 10;//1010 //unsigned n = 2;//把第二位1变为0,输出8 unsigned n = 3;//把第三位0变为1,输出14 //unsigned flag = 0;//flag为0把1变为0 unsigned flag = 1;//flag为1,把0变为1 setBit(&data, 3, 1); printf("%d\n", data); //double a = ; //printf("%f\n", pow(10.2,2)); //cout<<pow(10.2, 2); return 0; }

 

转载请注明原文地址: https://www.6miu.com/read-3850291.html

最新回复(0)