Binary Flags – library MetaTrader 5

You can use binary flags to minimize bool parameters in a function signature.

For example, MQL int size is 32 bits, so you can pack 32 1/0 parameters in a single int flag variable.

Before:

void Function(bool flag1,bool flag2,bool flag3,bool flag4,bool flag5,bool flag6,bool flag7,bool flag8,...flagN);

After:

void Function(int flags);

BinFlags can be initialized with any integer data type:char, bool, short, int, color, long, datetime.

Your maximum flag length will vary: 1 byte = 8 bits, 2 bytes = 16 bits, etc.

A flag represents a number which has only one ‘1’ bit in any position.

Such numbers are 1, 2, 4, 8, 16, 32, etc. You get it.

Large numbers of this kind look better in hex: 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, etc.

This class works with flags, which follow the rule.

BinFlags must be initialized first. You can overwrite later the internal flags with Write.

You can check, set, reset any number of flags.

Multiple flags should be separated by ‘|’.

template<typename T>class BinFlags
  {
public:
                     BinFlags():mflags(NULL) {} BinFlags(T flags):mflags(flags) {}
   void              Write(T flags) {mflags=flags;}
   T                 Read() {return mflags;}
   bool              Chk(T flags) {return (mflags&(flags))==flags;}
   void              Set(T flags) {mflags|=(flags);}
   void              Rst(T flags) {mflags&=~(flags);}
   string            Format();
protected:
   int               Bits() {int i=0; for(i; i<sizeof(T)*8; i+=4) {if(mflags<(int)pow(2,i)) {break;}} return (i)?i:1;}
   T                 mflags;
  };

Flag names can be enumerated for convenience.

Alternative:  Forex Fraus (for M1) Multi-currency - EA MetaTrader 4

Example of BinFalgs usage.

void OnStart()
  {
   BinFlags<int>bf(A|B);         //init & write
   /*MANIPULATE*/
   Print(bf.Format());           //0011 (2 flags on)
   Print("A:",bf.Chk(A));        //A:true
   Print("AD:",bf.Chk(A|D));     //AD:false
   bf.Set(C|D);                  //set C & D
   Print(bf.Format());           //1111 (all flags on)
   bf.Rst(A);                    //reset A
   Print("BCD:",bf.Chk(B|C|D));  //BCD:true
   Print(bf.Format());           //1110 (one flag down)
  }

Output:

/**
   BinFlags:0011
   A:true
   AD:false
   BinFlags:1111
   BCD:true
   BinFlags:1110
/**/


    📈 ROBOTFX MetaTrader Expert Advisors and Indicators to maximize profits and minimize the risks