简体   繁体   English

使用位的标志

[英]Flags using Bits

I'm trying to do simple bit operations on a 'char' variable; 我正在尝试对'char'变量进行简单的位操作; I would like to define 5 constants. 我想定义5个常数。

const int a = 0;
const int b = 1;
const int c = 2;
const int d = 3;
const int e = 4;

When I try to set more than one bit of the char, all bits apparently up to the set bit a read as set...here is code I use to set and read bits of the char var: 当我尝试设置char的多个位时,所有位显然都达到设置的位,并读为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

I read an incomplete thread that says that the operation to set bits may be different for x86...the system I'm using...is that the case here? 我读到一个不完整的线程说,对于x86,设置位的操作可能有所不同...我正在使用的系统...在这种情况下吗?

You're cutting into your other "bits"' space. 您正在切入其他“位”空间。 Examining a couple gives us: 检查一对夫妇可以给我们:

b = 1 = 0001
c = 2 = 0010
d = 3 = 0011 //uh oh, it's b and c put together (ORed)

To get around this, make each one represent a new bit position: 为了解决这个问题,使每个代表一个新的位位置:

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

You should consider not using 0 if there's a possibility of no bits being set meaning something different, too. 如果可能没有设置任何位,则也应该考虑不使用0。 The main application for this is to set and check flags, and no flags set definitely shows independence. 此方法的主要应用是设置和检查标志,并且没有设置标志肯定显示出独立性。

Change your definitions to because they way you have defined it some of them has more than one bit set 将您的定义更改为,因为它们以您定义它的方式,其中一些设置了多个位

const int a = 1 << 0;
const int b = 1 << 1;
const int c = 1 << 2;
const int d = 1 << 3;
const int e = 1 << 4;

This way it is evident that each constant only has 1 bit set. 通过这种方式,很明显每个常数只有1位设置。

If you want to learn all about the various bit hacks ... 如果您想全面了解各种黑客技术 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM