我需要检查是否为整数设置了某个标志.
我已经知道如何设置标志:
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)
我通常使用此功能:
// 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)
请注意,没有范围检查,只是为了性能。但如果您需要,很容易添加
您可以and
像&
在C ++中一样使用运算符。在数字参数上,它是按位的。这是按位运算的一些示例。
归档时间: |
|
查看次数: |
13633 次 |
最近记录: |