View Single Post
Codemonkey's Avatar Codemonkey Codemonkey is offline Super Moderator 2006-11-12 #27 Old  
024 - Bitflags by bitshifting
Last edited by Codemonkey : 2006-11-28 at 01:10.
&nbsp
When you add new flags, move them around or change them a lot, it can be an annoyance to have to update all the flag values each time, making sure they are unique and doubled each time.

To make things a little bit easier, you can use the bitshift operator. The bitshift operator 'knows' you want to store a value as a bit representation, like all the flags we've been defining. Here's an example:

ActionScript Code:
  1. var OLD_ONE = 1;
  2. var OLD_TWO = 2;
  3. var OLD_THREE = 4;
  4. var OLD_FOUR = 8;
  5.  
  6. var NEW_ONE     = 1 << 0; // shift bit 0 left
  7. var NEW_TWO     = 1 << 1; // shift bit 1 left
  8. var NEW_THREE   = 1 << 2; // shift bit 2 left
  9. var NEW_FOUR    = 1 << 3; // shift bit 3 left
  10.  
  11. trace(OLD_ONE == NEW_ONE); // "true"
  12. trace(OLD_TWO == NEW_TWO); // "true"
  13. trace(OLD_THREE == NEW_THREE); // "true"
  14. trace(OLD_FOUR == NEW_FOUR); // "true"
  15.  
Here's a more practical way:

ActionScript Code:
  1. var shifts:Number = 0;
  2.  
  3. var NEW_ONE     = 1 << shifts++; // 1
  4. var NEW_TWO     = 1 << shifts++; // 2
  5. var NEW_THREE   = 1 << shifts++; // 4
  6. var NEW_FOUR    = 1 << shifts++; // 8
  7.  
Now you can move the flags around without having to worry about their values.