我正在尝试对“char”变量进行简单的位操作; 我想定义 5 个常量。
const int a = 0;
const int b = 1;
const int c = 2;
const int d = 3;
const int e = 4;
当我尝试设置 char 的多个位时,所有位显然都达到设置位 a 读取为 set...这是我用来设置和读取 char var 位的代码:
char var = 0;
var |= c;
var|= d;
BOOL set = false;
if(var & b)
set = true; // reads true
if(var & c)
set = true; // also reads true
if(var & d)
set = true; // also reads true
我读到一个不完整的线程,它说设置位的操作对于 x86 可能不同...我正在使用的系统...这里是这种情况吗?
最佳答案
您正在切入其他“位”空间。检查一对夫妇给我们:
b = 1 = 0001
c = 2 = 0010
d = 3 = 0011 //uh oh, it's b and c put together (ORed)
为了解决这个问题,让每个代表一个新的位位置:
const int a = 0; //or 0x0
const int b = 1; //or 0x1
const int c = 2; //or 0x2 or 1 << 1
const int d = 4; //or 0x4 or 1 << 2
const int e = 8; //or 0x8 or 1 << 3
如果没有设置任何位也意味着不同的含义,您应该考虑不使用 0。这个的主要应用是设置和检查标志,没有设置标志肯定是独立的。
关于c++ - 使用位的标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11624001/