位运算的综合应用

This commit is contained in:
flykhan 2023-06-19 16:20:48 +08:00
parent 49565a55df
commit a53db5f59b
3 changed files with 46 additions and 0 deletions

15
day6/case1.cpp Normal file
View File

@ -0,0 +1,15 @@
// 案例1: data 为 1 字节 将 data 的第 3, 4 位清 0 其他位保持不变
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
char n = 0b01011011; // 0x5b = 0101 1011
cout << "原值: " << bitset<8>(n) << endl;
// 1000 | 10000 = 0001 1000 ; ~00011000 = 11100111
n &= ~(0x1 << 3 | 0x1 << 4);
cout << "结果: " << bitset<8>(n) << endl;
return 0;
}

16
day6/case2.cpp Normal file
View File

@ -0,0 +1,16 @@
// 案例2: data 为 1 字节, 将 data 的第 5, 6 为置 1 其他位保持不变
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
char n = 0b10001011; // 0x8b = 1000 1011
cout << "原值: " << bitset<8>(n) << endl;
// 1000 | 10000 = 0001 1000
n |= (0x1 << 5 | 0x1 << 6); // 将第 5, 6 位置为 1
cout << "结果: " << bitset<8>(n) << endl;
return 0;
}

15
day6/case3.cpp Normal file
View File

@ -0,0 +1,15 @@
// 案例3: data 为 1 字节, 将 data 的第 3, 4 位清0, 5, 6 置 1 其他位保持不变
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
char data = 0b10011011;
cout << "原值: " << bitset<8>(data) << endl;
data = (data & ~(0x1 << 3 | 0x1 << 4)) | (0x1 << 5 | 0x1 << 6);
cout << "结果: " << bitset<8>(data) << endl;
return 0;
}