Sign in to follow this  

using values in bitmasks and OR/AND evaluating them: example/explanation appreciated

Recommended Posts

This might be OT here, but i'll try anyway. I'm wanting to use bitmasks and using AND operation on them to see what options are passed in my main drawing loop. So for example, FLAGS=0x0; XYZ=0x1; in my keyboard function i have: case 'c': FLAGS|=XYZ; break; then i test in my main drawing loop if(FLAGS==XYZ) dostuff() but i can't get it to work. does anyone have an example maybe? I also would like to use something like ~XYZ so i only would need one keypress 'c' to turn the function XYZ on or off instead of OR'in it each time and assigning yet another keypress to it to turn it off. any examples/explanations would be greatly appreciated.

Share this post

Link to post
Share on other sites
| (bitwise or) is used to combine sets of bit flags. For example you have a bitset(of sorts):
_ 0111000000 (indicates user access to file only)
| 0110110000 (indicates the addition of r/w group access)
= 0111110000 (the result indiocates that a combination of the above permitions is used0

& (bitwise and) is used to test for a particular set of flags, or to single out a flag. For example:

_ 0111000000 (indicates user access to file only)
& 0100100100 (all flags that indicate a file can be read)
= 0100000000 (evaluates to true; the file can be read)

Share this post

Link to post
Share on other sites
You can use the bitwise exlusive or operator '^' to toggle options on and off. In your case:

case 'c':

As for your loop I think you were going about it the wrong way. If you want test if the XYZ option is turned on in flags then you want to use bitwise &:


FLAGS & XYZ should evalute to true if the options is turned on and false of the option is turned off.

Some useful bitwise operations:

bitwise OR | Used to combine options together or turn an option on.
bitwise AND & Used to test if an option is turned on.
bitwise NOT ~ If used with & it can turn an option off. (eg FLAG &= ~XYZ)
bitwise XOR ^ Used to toggle options on and off

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