Delphi中的按位标志

时间:2010-09-16 15:09:03

标签: delphi

我需要检查是否为整数设置了某个标志。

我已经知道如何设置标志:

flags := FLAG_A or FLAG_B or FLAG_C

但是如何检查是否设置了某个标志?

在C ++中我使用了&运算符,但是在Delphi中它是如何工作的?我现在有点困惑

3 个答案:

答案 0 :(得分:28)

在Delphi中,您有两个选择:

1)使用'和'运算符,如下所示:

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)定义集类型:

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

答案 1 :(得分:5)

您使用and运算符,就像使用C {+ &一样。在数字参数上,它是按位的。 Here are some examples按位运算。

答案 2 :(得分:5)

我通常使用这个功能:

// 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;

和二传手:

// 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;

请注意,没有范围检查,只是为了提高性能。但是如果你需要的话,很容易添加