Delphi:Bitfield Booleans
type TExplainThat =class(TObject) private FFlags:Cardinal; function GetFlags(Index:Integer):Integer; procedure SetFlags(Index:Integer;Value:Boolean); public property Flags[Index:Integer]:Boolean read GetFlags writeSetFlags; end;
function TExplainThat.GetFlags(Index:Integer):Integer; begin Result:=(FFlags and (1 shl Index) > 0); end;
procedure TExplainThat.SetFlags(Index:Integer;Value:Boolean); begin FFlags:=(FFlags xor ($7FFFFFFF and (1 shl Index))) or (ord(Value) shl Index); end;
- The
GetFlagsmethod is easy to understand. We simply check to see if the bit at position Index is turned on. -
SetFlagsis rather more complicated. In the first part - before theor- we turn off the bit at position Index. With this done we then turn it on again if Value istrue. Doing some math onord(Value)is more efficient than testing Value in anif..then..elseblock.
This technique enables up to 31 booleans to be stored in a 4 byte integer - a saving of 27 bytes! The performance hit incurred by doing some additional math is never noticeable - not even in the most complex of applications.