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;

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.

Jump To...

Colophon