Delphi中的按位标志

Mol*_*Mol 11 delphi

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

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

flags := FLAG_A or FLAG_B or FLAG_C
Run Code Online (Sandbox Code Playgroud)

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

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

klu*_*udg 30

在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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

  • +1提醒我一个聪明的裤子开发人员通过基本测试:((FLAG_A和Flags)= 1)而不是((FLAG_A和Flags)<> 0)造成大麻烦时发生的灾难它不起作用一点都没有!他将他的"性能提升"变为其中一个基类,因此我们开始在整个系统中出现细微的数据问题. (3认同)

Lut*_*hfi 6

我通常使用此功能:

// 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;
Run Code Online (Sandbox Code Playgroud)

和二传手:

// 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;
Run Code Online (Sandbox Code Playgroud)

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


T.J*_*der 5

您可以and&在C ++中一样使用运算符。在数字参数上,它是按位的。这是按位运算的一些示例

  • @Mol,结果也是C ++中的整数。C ++只是提供了从int到bool的自动转换,而Delphi要求您明确说明您的意思。通常的方法是与零进行比较,但是您也可以将结果类型转换为`LongBool`。 (4认同)
  • @Mol:使用“ &lt;&gt; 0”或“ = FLAG_A”来获取布尔值,例如“ if(标志和FLAG_A)&lt;&gt; 0”,则设置标志。如果该标志可能有多个位,则使用`if(标志和FLAG_A)= FLAG_A`(因为'&lt;&gt; 0'仅会测试是否至少设置了一个标志位,而不是全部设置) 。 (3认同)
  • @Mol:如果想要布尔值,请查看Serg的答案。使用一组并使用“输入”进行测试。帕斯卡(Pascal)不会做“任何事情都可以成为布尔值”的事情;实际上,我们大多数人都将其视为C的设计缺陷。在Pascal家族中,布尔值是布尔值,数字是数字,从设计的角度来看,它们彼此不是同一回事。 (2认同)