Bitwise flags in Delphi

前端 未结 3 1587
南方客
南方客 2020-12-16 16:39

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

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 17:18

    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

提交回复
热议问题