Bitwise Operations in MQL4

Bitwise operations are performed exclusively on integer types.

Complement to One (~)

  • Inverts all bits of a variable.
  • Syntax: b = ~n;
  • Example: char a='a', b; b = ~a; results in a = 97, b = -98.
  • Right Shift (>>)

  • Shifts the binary representation of x to the right by y digits.
  • **Unsigned types:** Logical right shift (fills with zeros).
  • **Signed types:** Arithmetic right shift (fills with sign bit).
  • Syntax: x = x >> y;
  • Example: char a='a'; b = a >> 1; results in b = 48.
  • Left Shift (<<)

  • Shifts the binary representation of x to the left by y digits.
  • Frees right-side digits are filled with zeros.
  • Syntax: x = x << y;
  • Example: char a='a'; b = a << 1; results in b = -62.
  • **Constraint:** Shifting by a number of bits greater than or equal to the variable's bit length results in undefined behavior.
  • Bitwise AND (&)

  • Performs a bitwise AND operation between x and y.
  • Result bit is 1 only if both corresponding bits in x and y are 1.
  • Syntax: b = ((x & y) != 0); (often used to check if a specific bit is set)
  • Example: char c = a & b; where a='a', b='b' results in c = 96.
  • Bitwise OR (|)

  • Performs a bitwise OR operation between x and y.
  • Result bit is 1 if at least one of the corresponding bits in x or y is 1.
  • Syntax: b = x | y;
  • Example: char c = a | b; where a='a', b='b' results in c = 99.
  • Bitwise Exclusive OR (^)

  • Performs a bitwise XOR operation between x and y.
  • Result bit is 1 if the corresponding bits in x and y are different.
  • Syntax: b = x ^ y;
  • Example: char c = a ^ b; where a='a', b='b' results in c = 3.
  • Related Topics

  • [Precedence Rules](/basis/operations/rules)