A bit field is an integer that is used to store a number of on/off flags (up to 32 flags per integer in NWScript). Each flag corresponds to a position in the binary (base 2) representation of an integer; the flag is considered "on" (or "set") if the binary digit (bit) in that position is a 1. Flags are often identified by the integer whose binary representation has just this designated digit being a 1.
Bit fields are often written in hexadecimal (base 16) notation, as this is more compact than binary notation and easier for human interpretation than decimal notation. Each hexadecimal digit represents four flags — 0x1, 0x2, 0x4, and 0x8 — that when added together give the value of that digit. (The decimal values 10 through 15 are represented in hexadecimal by the "digits" A through F.) Many calculators, including the scientific mode of the calculator program included with Windows, are capable of handling numbers in hexadecimal notation, which can be an aid to those unfamiliar with hexadecimal arithmetic. (The leading "0x" indicates that a number is in hexadecimal and is typically not used by calculators.)
Using[edit | edit source]
There are two basic ways to construct a bit field from individual flags. The first — addition (+) — is more useful for humans (i.e. when determining a value to use outside a script). As long as no two flags are the same, their values can be added together to produce a bit field with exactly those flags set. The second method — bitwise-or (|) — is more efficient for use in scripts, and it correctly handles the case where it is not known if no two flags are the same.
When testing a bit field for a particular flag, the bitwise-and operator (&) is used. If combining a bit field and a flag with the &-operator produces a true value (not necessarily the special value TRUE), then the flag is set. Otherwise, the result is a false value and the flag is not set.
Flags can be unset by combining the bitwise-and with the bitwise-negation (~). Combining a a bit field and the bitwise-negation of a flag with the &-operator produces a bit field with the flag cleared.
// Defining a symbolic constant for a flag. const int FLAG_6 = 0x0020;
// Constructing a bit field from symbolic constants. int nBitField = FLAG_1 | FLAG_2 | FLAG_13;
// Testing a flag. if ( nBitField & FLAG_5 )
// Clearing a flag nBitField = nBitField & ~FLAG_7;