Subcribe via RSS

Bit masking for flag parameters in AS3

June 14th, 2011 | Posted in ActionScript3

Sometimes it’s pretty handy the use of bit operations in our daily projects. One of the situations where this solution is very useful is when we need a function that expects an undefined number of flag parameters.

Let’s have a look at the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
var MY_FIRST_FLAG:int  = 1;
var MY_SECOND_FLAG:int = 2;
var MY_THIRD_FLAG:int  = 4;
var MY_FORTH_FLAG:int  = 8;

function myFunction(flags:int):void {
  if (flags & MY_FIRST_FLAG)  trace("first flag enabled");
  if (flags & MY_SECOND_FLAG) trace("second flag enabled");
  if (flags & MY_THIRD_FLAG)  trace("third flag enabled");
  if (flags & MY_FORTH_FLAG)  trace("forth flag enabled");
}

myFunction(MY_FIRST_FLAG | MY_THIRD_FLAG);

The first thing to notice is how we create the flag values. We need a list of values that don’t overlap in binary. In order to do so we first need to understand how integer values are represented in binary. Following we can see the first four integer values:

1: 0001
2: 0010
3: 0011
4: 0100

What we need is that every bit represents a flag. The bit set as 1 will mean the flag is enabled when 0 will be the flag is disabled.

We cannot use all the integer values as the binary representation may overlap as the following example where value 3 overlaps with the combination of value 1 and value 2:

1: 0001
2: 0010
————
3: 0011

In order to avoid overlapping in binary we have to use a value that doubles the previous one every time. A list that suits that would be: 1, 2, 4, 8, 16, 32, 64, 128, 256 and so on.

Now let’s have a look at what the function does. We receive an integer parameter for the flags. We will need to apply the AND (&) bit operation that will fill with 1 the bit positions when there are two 1 and left 0 otherwise. What this means is that we will get the value of the flag integer after the AND bit operation if the bit mask is 1 or a value of 0 is the bit mask is 0.

See the following example to understand how the AND bit operation works:

1
2
3
4
5
0011 (example flags value)
&
0010 (flag MY_SECOND_FLAG)
------------
0010 (result different of 0: the bit of the flag is 1)

The final step is when we call the function. We will need to use the OR (|) bit operation to add the bit mask to our parameter. Let’s see how the OR bit operation works with an example:

1
2
3
4
5
0001 (flag MY_FIRST_FLAG)
|
0010 (flag MY_SECOND_FLAG)
------------
0011 (result with both bit masks as 1)

In our ActionScript example we send the flags MY_FIRST_FLAG and MY_THIRD_FLAG, and if we run the code we will get in the output the trace messages confirming that these two flags are enabled.

Bit operations can be quite confusing at first as we are not used to work too much with them, but we can simplify functions and make code much more clear avoiding lots of flag parameters in functions.


Happy coding!

Leave a Reply