Bitwise & logical operators

The same operators do two jobs

AND, OR, XOR, NOT work on:

  • BOOL — logical operations. xA AND xB is the logical AND of two booleans.
  • BYTE/WORD/DWORD/LWORD — bitwise operations. bA AND bB is the bitwise AND of every bit-pair.

The operand type decides which. Mixing BOOL and a multi- bit type in one operation is illegal (matiec rejects it).

& is a synonym for AND (both equally valid). The IEC standard prefers AND; some older code uses &.

Operators

OpMeaningBOOL operandsBit-string operands
NOTNegationNOT xA flips the boolNOT bA flips every bit
AND, &Conjunctionlogical ANDbitwise AND
ORDisjunctionlogical ORbitwise OR
XORExclusive ORlogical XORbitwise XOR

There are no shift operators in the operator set — SHL/SHR/ROL/ROR are functions, called like SHL(IN, N). See the Standard Library bit functions page (stub) and the matiec emit-bug warning in llm_signals above.

Examples

(* logical *)
xReady := xEnable AND NOT xFault;
xAny   := xA OR xB OR xC;

(* bitwise *)
bMask  := bByte AND 16#0F;       (* keep low nibble *)
bToggle := bByte XOR 16#80;      (* flip top bit *)

(* bit-access — read one bit out of a multi-bit type as BOOL *)
xLowBit := bByte.0;
bSet    := bByte.7;

(* construct a multi-bit value from individual bools *)
(* IEC has no first-class "bool to bit" — use SEL: *)
bByte := SEL(xA, BYTE#0, BYTE#1)
       OR SEL(xB, BYTE#0, BYTE#2)
       OR SEL(xC, BYTE#0, BYTE#4);

Bit-access syntax

For any BYTE/WORD/DWORD/LWORD variable named bx, the expression bx.N accesses bit N (0 = least-significant) as a BOOL. This works for both reads and writes:

xFlag := bMask.3;     (* read bit 3 of bMask as BOOL *)
bMask.5 := TRUE;      (* set bit 5 of bMask *)

Bit-access only works on bit-string types, not on integer types like INT. If the variable is an integer, convert first (INT_TO_WORD).

Short-circuit evaluation

The IEC standard does not mandate short-circuit evaluation for AND / OR. Both operands can be evaluated even when the first one already determines the result. Don’t rely on xPtrValid AND xPtr.SomeField to skip the field-access when xPtrValid is FALSE — that is an unsafe idiom in IEC ST.

In practice matiec does evaluate left-to-right and stops on the first definitive value, but this is not portable to other IEC compilers.

IEC reference

IEC 61131-3 third edition (2013), clause 6.6.1 Table 55.

matiec conformance

matiec implements AND / OR / XOR / NOT per the standard for both BOOL and bit-string operands. The well-known emit-bug with SHL(BYTE#1, …) is an emit-bug on shift functions, not on the bitwise operators themselves — the operators work correctly. See the second llm_signals entry above for the workaround.