Bitmasks in Java
January 6, 2010
If you need to store multiple boolean flags for something, you can do it using bits and storing that inside a single integer. The examples below use Java, but this is possible in most languages.
First, some constants:
public static final int FLAG_A = 1; // Binary 00001 public static final int FLAG_B = 2; // Binary 00010 public static final int FLAG_C = 4; // Binary 00100 public static final int FLAG_D = 8; // Binary 01000
Setting A Flag
To set a flag, use the bitwise OR operator:
int lFlags = 0; lFlags = lFlags | FLAG_C;
Checking A Flag
To test the value of a flag, use bitwise AND:
boolean lFlagCSet = false; if ((lFlags & FLAG_C) == FLAG_C) { lFlagCSet = true; }
This can be simplified (and made slightly harder to read) as:
boolean lFlagCSet = ((lFlags & FLAG_C) == FLAG_C);
Flipping Bits
To change the value of a flag (ie if it's set, unset it; if it's unset, set it) use the ~ operator:
lFlags = lFlags & ~FLAG_C;
To flip all the bits:
lFlags = ~lFlags
More Details
A Java int can hold 31 flags this way. The int is a 32-bit datatype, but the final bit is reserved for the plus/minus sign.
For more details see http://www.vipan.com/htdocs/bitwisehelp.html