« I'm getting married! | Home | Migrating from svn to git »

December 21, 2008

ActionScript 3: Bitwise Flags

The other day i was chatting with a friend about element flags. I remember about bitwise flags. I was surprised he didn't know about them so i thought why not share it with everybody :)

Bitwise flags are used in the Alert component in flash for example. The show method expects the button options: Alert.OK | Alert.CANCEL for example.

Each of this properties have a uint value (bit value to be exact), smth like this for example:
public const OK:uint = 1; public const CANCEL:uint = 2; public const YES:uint = 4; public const NO:uint = 8;

Remember they are bit values, that's why i don't use a perfect numerical increment.

Check out this example:
// let's add the YES and NO flags public var flags:uint = YES | NO; // this is the same as doing the following: // flags |= YES; // flags |= NO;

Now in order to check if a flag has been set:
if((flags & YES) == YES) trace ("YES flag is set"); if((flags & NO) == NO) trace ("NO flag is set"); if((flags & OK) == OK) trace ("OK flag is set"); // the way i always do this is the following because if the flag exists it will return a // number different than 0 // if(flags & YES) trace ("YES flag is set");

Now, how do we unset a flag? Easy!
// remove the NO flag flags ^= NO; if(flags & NO) trace ("NO flag is set"); // No trace so successfully unset! :)

Hope this helps you somehow :)

--fernando

2 Comments

very nice fer ;)

I have to use this! o_o

About this Entry

This page contains a single entry by fernando published on December 21, 2008 12:54 PM.

I'm getting married! was the previous entry in this blog.

Migrating from svn to git is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.