使用C++中的宏进行二进制操作,可以通过位操作符来实现。以下是一些常见的位操作符及其用法:
#include<iostream>
using namespace std;
int main() {
int a = 10; // 1010 in binary
int b = 7; // 0111 in binary
int c = a & b; // 0010 in binary, which is 2 in decimal
cout << "Result of bitwise AND: " << c << endl;
return 0;
}
#include<iostream>
using namespace std;
int main() {
int a = 10; // 1010 in binary
int b = 7; // 0111 in binary
int c = a | b; // 1111 in binary, which is 15 in decimal
cout << "Result of bitwise OR: " << c << endl;
return 0;
}
#include<iostream>
using namespace std;
int main() {
int a = 10; // 1010 in binary
int b = 7; // 0111 in binary
int c = a ^ b; // 1101 in binary, which is 13 in decimal
cout << "Result of bitwise XOR: " << c << endl;
return 0;
}
#include<iostream>
using namespace std;
int main() {
int a = 10; // 1010 in binary
int b = ~a; // 0101 in binary, which is -11 in decimal
cout << "Result of bitwise NOT: " << b << endl;
return 0;
}
#include<iostream>
using namespace std;
int main() {
int a = 10; // 1010 in binary
int b = a << 2; // 101000 in binary, which is 40 in decimal
cout << "Result of left shift: " << b << endl;
return 0;
}
#include<iostream>
using namespace std;
int main() {
int a = 10; // 1010 in binary
int b = a >> 2; // 0010 in binary, which is 2 in decimal
cout << "Result of right shift: " << b << endl;
return 0;
}
通过这些位操作符,可以实现对二进制数据的各种操作,包括设置、清除、切换某个位的值等。
领取专属 10元无门槛券
手把手带您无忧上云