开发者

Bitwise flags in Delphi

开发者 https://www.devze.com 2023-01-16 05:20 出处:网络
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

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


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


I usually use this function:

// Check if the bit at ABitIndex position is 1 (true) or 0 (false)
function IsBitSet(const AValueToCheck, ABitIndex: Integer): Boolean;
begin
  Result := AValueToCheck and (1 shl ABitIndex) <> 0;
end;

and the setters:

// set the bit at ABitIndex position to 1
function SetBit(const AValueToAlter, ABitIndex: Integer): Integer;
begin
  Result := AValueToAlter or (1 shl ABitIndex);
end;

// set the bit at ABitIndex position to 0
function ResetBit(const AValueToAlter, ABitIndex: Integer): Integer;
begin
  Result := AValueToAlter and (not (1 shl ABitIndex));
end;

Note there is no range checking, just for performance. But easy to add if u need to


You use the and operator as you would & in C++. On numeric arguments, it's bitwise. Here are some examples of bitwise operations.

0

精彩评论

暂无评论...
验证码 换一张
取 消