Sign in to follow this  
Misery

Bitset data access operator problem

Recommended Posts

Misery    354
Hello,

I am in a need of creating a bitset. However I cannot think of any solution how to make an operator that would set the proper bit to true or false in such manner:

[code]
bitset(i)=true;
bitset(j)=false;
[/code]

where i, j are the bits i want to set to proper value.

I have checked BOOST dynamic bitset, however I cannot figure out the soution. I know that I have to use some helper class. This is where I'm stuck. Very simplified, the problem is:

[code]
class Block //helper class
{
public:
int Container;
int mask; //how do I set the mask?

Block& operator=(bool x) { Assign(x); return *this; }

void Assign(bool x) { x? do_set() : do_reset(); }
void do_set() { Container |= mask; }
void do_reset() { Container &= ~mask; }
};

class bitset
{
public:
int Data[4]; //array of ints - here only 4
int cs; //container size

bitset()
{
cs=sizeof(int)*8;
}

int operator () (int i) const
{
return Data[i/cs] & (1 << (i%cs));
}

int& operator () (int i) //int, bool or whatever, Block?? I have no idea
{
//what do I add here to be able to do substitution like mentioned above?
}
};
[/code]

Thanks in advance for any sugestions,
Misery Edited by Misery

Share this post


Link to post
Share on other sites
alvaro    21246
I didn't read the code you posted, but I know how to solve your problem. You define an `operator()(int)' --although I would prefer `operator[](int)', so it looks more like an array-- that returns an object that contains enough information to locate the bit. Something like this:
[code]class BitReference {
unsigned char *byte;
int bit;

// ...
};[/code]

You then define `operator=(bool)' for that object in the obvious way. You probably also want to provide an implicit conversion to `bool'.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this