a tiny bit of bitmasking

Bit masks are good for managing many boolean values within a class. For example, here is a theoretical Alert class, which can show any combination of five buttons: OK, YES, NO, CANCEL, MAYBE. Instead of creating a boolean property for each of these, we can store all this info on one property (in this example the flags property).

Firstly, for readability, we can map each button type to an uint as an enumerated constant:

public static const AlertButtons.OK:uint = 1;
public static const AlertButtons.YES:uint = 2;
public static const AlertButtons.NO:uint = 4;
public static const AlertButtons.CANCEL:uint = 8;
public static const AlertButtons.MAYBE:uint = 16;

then, these constants can be applied to the flags property using the bitwise OR operator ( | ).

myAlertBox.flags = ( AlertButtons.YES | 
                     AlertButtons.NO | 
                     AlertButtons.MAYBE )

We can then test the flags property against the enumerated value for each button using the bitwise AND operator ( & ).

if (flags & AlertButtons.OK) trace("OK");
if (flags & AlertButtons.YES) trace("Yes");
if (flags & AlertButtons.NO) trace("No");
if (flags & AlertButtons.CANCEL) trace("Cancel");
if (flags & AlertButtons.MAYBE) trace("Maybe");

Leave a Reply

Your email address will not be published. Required fields are marked *