Bit Flags
A Programming Pattern |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
if
statements that will have boolean
expressions that involve the variables that represent the
itemsboolean
variable for each item
that is assigned true
when the player has the item and
false
otherwise
int
is represented using multiple bits&
,
|
, and ^
operators|
operator, clear particular bits (i.e.,
make the bits 0) using the &
operator, and/or
toggle particular bits (i.e., switch the bits to their other value)
using the ˆ
operator|
operator and a relational operator00000001
,00000010
,00000100
,
00001000
,00010000
,00100000
,
and 01000000
|
operator00000001 | 01000000 ________ 01000001
/** * Returns true if any of the bits in the parameter named needed are * set in the parameter named actual. * * @param needed The flags that need to be 1 * @param actual The bits that are actually set * @return true if any of the bits in named are set in actual */ public static boolean anyOf(int needed, int actual) { return (needed & actual) > 0; }
/** * Returns true if all of the bits in the parameter named needed are * set in the parameter named actual. * * @param needed The flags that need to be 1 * @param actual The bits that are actually set * @return true if all of the bits in named are set in actual */ public static boolean allOf(int needed, int actual) { return (needed & actual) == needed; }
/** * Returns true if exactly the bits in the parameter named needed are * set in the parameter named actual. * * @param needed The flags that need to be 1 * @param actual The bits that are actually set * @return true if only the bits in named are set in actual */ public static boolean onlyOf(int needed, int actual) { return (needed == actual); }
public static final int FOOD = 1; public static final int SPELL = 2; public static final int POTION = 4; public static final int WAND = 8; public static final int WATER = 16; // And so on...
int inventory; inventory = 0;