Sign in to follow this  
rangler

Unity [java] bitmasking and flags

Recommended Posts

You could do something like the following:


public static final int MASK_ONE = 1;
public static final int MASK_TWO = 2;
public static final int MASK_FOUR = 4;

// some logic...

if(someValue == (MASK_ONE | MASK_TWO | MASK_FOUR))
{
// do something
}


It really depends on what you are trying to achieve, but this approach should work.

Share this post


Link to post
Share on other sites
Quote:
Original post by Whackjack

if(someValue == (MASK_ONE | MASK_TWO | MASK_FOUR))
{
// do something
}



Better write:

if ((someValue & (MASK_ONE | MASK_TWO)) != 0)
{
// do something if MASK_ONE or MASK_TWO is set
}

Share this post


Link to post
Share on other sites
Two things to consider here:

- First, if you're going to use C/C++ style enums, you must be aware that you have to use bit flags, that is, values must be a power of 2, as it is in Whackjack's example. This is fine and fast, but it can lead to problems if you have a large set of enum constant types.

- To solve this, the SDK 1.5 introduced the implementation of enums. They are backed by the same system, with a limit of 64 if I remember well, which makes people complain a lot about it ;)

However, using enums is quite simpler than the suggested approach if you stick to the java.util.EnumSet class. A bit more on java enums can be found here

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