Bitwise flags in Delphi

前端 未结 3 1589
南方客
南方客 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:45

    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
    

提交回复
热议问题