Bit Flags

It is possible to store many boolean states in a single integer value and test the values quickly using bit testing. For example, we could have a variable of type byte, which can then be used to represent eight states for the eight bits it contains. First of all, we can declare our eight mask values. We would first need to specify the values for the masks to represent the position of the bits that we want to test.

byte ROCKETS = 1; byte LASERS = 2; byte SHIELDS = 4; byte INVINCIBLE = 8; byte AUTO_PILOT = 16; byte AIR_CONDITIONING = 32; byte TRACTOR_BEAM = 64; byte WINDOW_WIPERS_ON = 128;

The values are all powers of two to represent each bit in the 8-bit value. For example, the AUTO_PILOT mask has a value of 16, which in binary form is the value 10000, to which we can then test the fifth bit in our state variable to see whether it is true or false and also set this value. So for example, let's say we have a variable, state, and we want to initialize this value to represent data indicating that the ship's rockets are on, the shields are active, and the air conditioning is on too, as it can get awfully hot in there. We can set these flags as follows:

byte state = ROCKETS | SHIELDS | AIR_CONDITIONING;

As you can see it is a neat and easy-to-read system, saves memory, and is fast too. Here we have effectively set the variable state to the binary value 00100101. You can see that these bits correspond to the masks that we have used. We may then want to turn off the air conditioning, which we would perform as follows:

state &= ~AIR_CONDITIONING;

You can set the state, say, of invincibility of the ship to true/on, as follows:

state |= INVINCIBLE;

You can test the individual states as follows:

if((state & ROCKETS) > 0)     System.out.println("Fire when ready");

You can also combine the masks and create new masks for given scenarios. For instance, we could say that if we have rockets and window wipers on at the same time, we are unbeatable. We would then create a new mask for the unbeatable scenario.

byte UNBEATABLE = ROCKETS | WINDOW_WIPERS_ON;     if((state & UNBEATABLE) > 0)     System.out.println("We can see the danger, lemony fresh");

Well, that's enough playing with my bits, as my mother used to say.



Java 1.4 Game Programming
Java 1.4 Game Programming (Wordware Game and Graphics Library)
ISBN: 1556229631
EAN: 2147483647
Year: 2003
Pages: 237

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net