Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if flag is set in integer variable

I am making my own simple drawing engine. I am trying to determine if a variable has been set to a specific value using what I think is called bitwise comparison but I maybe wrong.

I've always been a bit confused about what the following is and how I use it:

int DRAW_REPEAT_X = 70001; // I have a feeling I should make this value binary instead of a unique number, ie, 0
int DRAW_REPEAT_Y = 70002; // I have a feeling I should make this value binary instead of a unique number, ie, 2
int drawMethod    = DRAW_REPEAT_X | DRAW_REPEAT_Y; // this means I want to repeat an image on both the x and y axis doesn't it?

// Now I want to check if drawMethod has DRAW_REPEAT_X set: this is where I struggle to know how to check this
// Is the following correct?
if (drawMethod && DRAW_REPEAT_X) {
  // the user wants me to repeat an image along the x axis
}

// Now I want to check if drawMethod has DRAW_REPEAT_Y set: this is where I struggle to know how to check this
if (drawMethod && DRAW_REPEAT_Y) {
  // the user wants me to repeat an image along the x axis
}

Is the following code correctly checking if DRAW_REPEAT_X is set? It always returns 1 in my anding check.

EDIT And to check whether both bits are set do I do this?

if (drawMethod & DRAW_REPEAT_X & DRAW_REPEAT_Y) {
   // both set
}

// OR

if (drawMethod & DRAW_REPEAT_X && drawMethod & DRAW_REPEAT_Y) {
   // both set
}
like image 833
sazr Avatar asked Jul 21 '26 22:07

sazr


1 Answers

No it isn't, you should use the bitwise AND operator instead - & and set the flags as binary values - your intuition is correct on that side.

A common trick to setting specific bits is using the shift operator:

int DRAW_REPEAT_X = 0x1 << 0;  //first bit set to 1, others 0
int DRAW_REPEAT_Y = 0x1 << 1;  //second bit set to 1, others 0

and check the int as

if (drawMethod & DRAW_REPEAT_X)  //check it that particular flag is set, ignore others
{
}
like image 76
Luchian Grigore Avatar answered Jul 23 '26 14:07

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!