Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise flags in Delphi

Tags:

delphi

I need to check if a certain flag is set for an integer.

I already know how to set a flag:

flags := FLAG_A or FLAG_B or FLAG_C

But how can I check if a certain flag is set?

In C++ I used the & operator, but how does that work in Delphi? I'm a bit confused at the moment

like image 452
Mol Avatar asked Sep 16 '10 15:09

Mol


People also ask

What is a Bitwise flag?

Bit flags are one or more (up to 32) Boolean values stored in a single number variable. Each bit flag typically has a corresponding predefined constant associated with it; this constant has the bit for this flag set to 1 and all other bits set to 0.

How do I find a Bitwise flag?

To check a flag state, we use bitwise AND operator (&). It allows to determine if bit is on or off.


1 Answers

In Delphi you have 2 options:

1) use 'and' operator, like this:

const
  FLAG_A = 1;  // 1 shl 0
  FLAG_B = 2;  // 1 shl 1
  FLAG_C = 4;  // 1 shl 2

var
  Flags: Integer;

[..]
  Flags:= FLAG_A or FLAG_C;
  if FLAG_A and Flags <> 0 then ..  // check FLAG_A is set in flags variable

2) define set type:

type
  TFlag = (FLAG_A, FLAG_B, FLAG_C);
  TFlags = set of TFlag;

var
  Flags: TFlags;

[..]
  Flags:= [FLAG_A, FLAG_C];
  if FLAG_A in Flags then ..  // check FLAG_A is set in flags variable
like image 93
kludg Avatar answered Sep 19 '22 23:09

kludg