Usually you check if a specific bit is set in the Integer variable using the binary operator and , and you set the individual bits using the or operator, for example:
const OPTION_X = $01; OPTION_Y = $02; OPTION_Z = $04; var Options: Byte; begin Options := OPTION_X or OPTION_Y; //actually 3, like in your example //check if option_X is set if (Options and OPTION_X) = OPTION_X then ShowMessage('Option X is set'); //this message is shown, because the bit is set //check if option_Z is set if (Options and OPTION_Z) = OPTION_Z then ShowMessage('Option Z is set'); //this message is NOT shown end;
The various OPTION_ constants are actually masks , in the sense that they are used to mask bits to zero (to check bits) or to mask bits to 1 (to set a specific bit).
Consider this snippet:
begin .. if cbOptionX.Checked then Options := Options or OPTION_X; ..
or mask the first bit to 1. If we start with the parameter value (in binary terms) 01010000, then the parameters will be 01010001 as a result
01010000 OR 00000001
the same value is used to mask all other bits to 0 to check if a particular bit is set. The if condition, for example: (Options and OPTION_Z) = OPTION_Z , does the following:
first, it starts all uninterested bytes of the Option variable at 0. If we look at the last value 01010001, the operation will clear all the bits, but the first.
01010001 AND 00000001 = 00000001
given the initial value 01010000, it will return zero:
01010000 AND 00000001 = 00000000
- next, it compares if this value is equal to the mask itself. If it is equal, the bit was set in the original Options variable, otherwise it was not set. If your mask contains only one bit, as far as taste is concerned, you can simply check if the resulting value, for example, is different from 0, but if your mask contains several bits, and you want to check if all bits have been set, you should check equality.
source share