ontherocks
ontherocks

Reputation: 1959

Bit Masks: Set different states of an object via set method

I have a material which can be either HOT or COLD, WHITE or BLACK. The states can be HOT and WHITE, HOT and BLACK, COLD and WHITE, COLD and BLACK. I have the following class

   class myMaterial
    {
    public:
        enum state
        {
            DEFAULT     = 0,
            HOT         = 1 << 0,
            WHITE       = 1 << 1
        };

        void SetState(int);

    private:
        int m_state;
    };


    void myMaterial::SetState(int state)
    {
        m_state = state;
    }

Now in main(), I call the SetState method to set these states

myMaterial material;
material.SetState(myMaterial::HOT);

Is the following bitwise operations correct, to set all the types of states

HOT and WHITE  =>  myMaterial::HOT | myMaterial::WHITE
HOT and BLACK  =>  myMaterial::HOT | ~myMaterial::WHITE
COLD and WHITE =>  ~myMaterial::HOT | myMaterial::WHITE
COLD and BLACK =>  ~myMaterial::HOT | ~myMaterial::WHITE

Upvotes: 0

Views: 99

Answers (2)

adrin
adrin

Reputation: 4886

No.

Using ~ means negating all the bits; which I suppose is not what you want, as it results in lots and lots of 1s in your representation (all except one single bit). You're having 3 states for each status, for example cold, hot, and don't know. So you'll need 2 bits for them, not 1.

Edit

Now the question is changed, but if we assume you still have 3 states for each bit, you will need two bits. So assume you have a COLD and HOT state. Then:

HOT = 1 << 0;
COLD = 1 << 1;

And then if you want to set the variable var to COLD, making sure it's not HOT, you'll need to do:

var = (var | COLD) // add coldness
var = var & ~HOT // remove hotness

Or equivalently:

var = (var | COLD) & ~HOT

Upvotes: 1

user555045
user555045

Reputation: 64904

After the edit, the question seems to be a little different, and doesn't require @adrin's solution of 2 bits per property any more.

Now it's just:

HOT and WHITE = myMaterial::HOT | myMaterial::WHITE
HOT and BLACK = myMaterial::HOT
COLD and WHITE = myMaterial::WHITE
COLD and BLACK = 0

If you add an extra bit that says whether the state is known or not:

UNKNOWN = 0
HOT and WHITE = myMaterial::HOT | myMaterial::WHITE | myMaterial::KNOWN
HOT and BLACK = myMaterial::HOT | myMaterial::KNOWN
COLD and WHITE = myMaterial::WHITE | myMaterial::KNOWN
COLD and BLACK =  myMaterial::KNOWN

Upvotes: 1

Related Questions