简体   繁体   中英

Flags using Bits

I'm trying to do simple bit operations on a 'char' variable; I would like to define 5 constants.

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 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?

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. 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.

If you want to learn all about the various bit hacks ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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