# Logical & Bit Instructions

Source: https://rungs.dev/docs/ladder-logic/instructions/logical

> Reference for Ladder Logic bit instructions in rungs.dev — AND, OR, XOR, NOT, SWPB, CLR, and BTD — combining, flipping, reordering, clearing, and relocating the bits and bytes of a word.

A `DINT` is 32 individual bits. These instructions work on those bits directly: `AND`, `OR`, and `XOR` combine two words bit-by-bit; `NOT` flips every bit of one word; `SWPB` puts a word's bytes in a different order; `CLR` clears all 32 bits to `0`; and `BTD` moves a run of bits from one position to another. Reach for them when a tag is a _bundle of flags_ rather than a single number — packing several on/off signals into one word, pulling one flag back out, clearing a scratch register, or flipping a bit without disturbing its neighbors.

Like the math instructions, they act as outputs — place them on the right side of a rung, and they run once per scan while the rung is true. They share the **Move/Logical** tab with [`MOVE` and `MVM`](https://rungs.dev/docs/ladder-logic/instructions/move).

## Available Instructions [#available-instructions]

| Instruction | Symbol                            | Purpose                                                                                                                                                                                  |
| ----------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `AND`       |   | Writes the bitwise AND of Source A and Source B into the destination tag. Each result bit is 1 only where both source bits are 1.                                                        |
| `OR`        |    | Writes the bitwise OR of Source A and Source B into the destination tag. Each result bit is 1 where either source bit is 1.                                                              |
| `XOR`       |   | Writes the bitwise exclusive-OR of Source A and Source B into the destination tag. Each result bit is 1 where the two source bits differ.                                                |
| `NOT`       |   | Writes the bitwise complement of the source into the destination tag. Every 0 bit becomes 1 and every 1 bit becomes 0.                                                                   |
| `SWPB`      |  | Writes the Source with its bytes in a new order into the destination: REVERSE turns the bytes round, WORD swaps the two halves of a DINT, and HIGH/LOW swaps the bytes within each half. |
| `CLR`       |   | Clears the destination tag to 0.                                                                                                                                                         |
| `BTD`       |   | Copies a run of bits from the Source into the destination starting at a chosen bit, leaving the other destination bits unchanged.                                                        |

## Operands [#operands]

`AND`, `OR`, `XOR`:

| Name      | Type                                |
| --------- | ----------------------------------- |
| `sourceA` | `DINT` \| `INT` \| `SINT` \| `REAL` |
| `sourceB` | `DINT` \| `INT` \| `SINT` \| `REAL` |
| `dest`    | `DINT` \| `INT` \| `SINT` \| `REAL` |

`NOT`:

| Name     | Type                                |
| -------- | ----------------------------------- |
| `source` | `DINT` \| `INT` \| `SINT` \| `REAL` |
| `dest`   | `DINT` \| `INT` \| `SINT` \| `REAL` |

These are bit operations, so the natural operand is a `DINT`. A `REAL` source is allowed but is first converted to a `DINT` (banker rounding) before the bits are combined — you rarely want that. A `BOOL` is **not** accepted: to combine single on/off bits, use ladder contacts (series for AND, a parallel branch for OR), not these instructions.

## Bit by bit [#bit-by-bit]

For any single bit position, the four instructions do this:

| Source A bit | Source B bit | `AND` | `OR` | `XOR` |
| ------------ | ------------ | ----- | ---- | ----- |
| `0`          | `0`          | `0`   | `0`  | `0`   |
| `0`          | `1`          | `0`   | `1`  | `1`   |
| `1`          | `0`          | `0`   | `1`  | `1`   |
| `1`          | `1`          | `1`   | `1`  | `0`   |

`NOT` needs no table — it simply inverts each bit.

Writing masks in [hexadecimal or binary](https://rungs.dev/docs/structured-text/arithmetic-and-comparison-operators) makes the bit pattern obvious: `16#0000_00ff` is the low 8 bits, `2#0000_0100` is bit 2 alone.

## Example — pull one byte out of a word (AND masks) [#example--pull-one-byte-out-of-a-word-and-masks]

`AND` with a mask keeps only the bits the mask has set to `1` and forces the rest to `0`. To read just the low byte of a status word:

```ladder
AND(StatusWord,16#0000_00ff,LowByte)
```

If `StatusWord` is `16#0000_12ab`, then `LowByte` becomes `16#0000_00ab` — the high half is masked away.

## Example — set and clear a flag (OR / AND) [#example--set-and-clear-a-flag-or--and]

Store several independent flags in one `DINT`, each on its own bit. `OR` turns a bit **on** without touching the others; `AND` with the _inverted_ mask turns one **off**.

```ladder
XIC(In_Fault)OR(Alarms,2#0100,Alarms);XIO(In_Fault)AND(Alarms,16#ffff_fffb,Alarms)
```

The first rung sets bit 2 of `Alarms` while `In_Fault` is on; the second clears bit 2 (mask `16#ffff_fffb` has every bit set _except_ bit 2) when the fault is gone. The other alarm bits keep their values either way.

## Example — toggle a bit (XOR) [#example--toggle-a-bit-xor]

`XOR` against a mask flips exactly the bits the mask sets. A one-shot on the rung makes each press flip the bit once:

```ladder
XIC(In_Press)ONS(EdgeBit)XOR(Mode,2#0001,Mode)
```

Every press flips bit 0 of `Mode` between `0` and `1`.

## NOT — inverting a whole word [#not--inverting-a-whole-word]

`NOT` flips all 32 bits of its source. Because a `DINT` is _signed_, an all-`0` word inverts to all `1`s, which reads as `-1`:

```ladder
NOT(16#0000_000f,Inverted)
```

Here `Inverted` becomes `16#ffff_fff0` (decimal `-16`). `NOT` of `0` is `-1`; `NOT` of `-1` is `0`.

> **WARNING**
>
> **NOT is not a contact**
>
> This `NOT` inverts a whole `DINT` word — it is **not** a way to invert a single contact on a rung. To pass power when a bit is `0`, use a normally-closed contact ([`XIO`](https://rungs.dev/docs/ladder-logic/instructions/xio)). `NOT` and `XIO` solve different problems.

## SWPB — swap bytes [#swpb--swap-bytes]

A `DINT` is 4 bytes and an `INT` is 2. Not every device stores them in the same order. A drive,
a scale or a gateway that sends a number or text in Modbus registers often puts the bytes the
other way round, so a value that should be `16#1234` arrives as `16#3412`, and text arrives
with each pair of letters swapped: `'ABCRDO1E'` where the device sent `'BARCODE1'`.
`SWPB` puts the bytes back in order.

| Name        | Type            | Notes                                       |
| ----------- | --------------- | ------------------------------------------- |
| `source`    | `DINT` \| `INT` | a tag, never a number typed in              |
| `orderMode` | a word          | `REVERSE`, `WORD` or `HIGH/LOW`, or `0`–`2` |
| `dest`      | `DINT` \| `INT` | the same type as `source`, or a `DINT`      |

Picture a `DINT` as four bytes `A B C D`, with `A` the highest. The order mode says where they
go:

| Order mode | Number | `A B C D` becomes | `16#1234_5678` becomes |
| ---------- | ------ | ----------------- | ---------------------- |
| `REVERSE`  | `0`    | `D C B A`         | `16#7856_3412`         |
| `WORD`     | `1`    | `C D A B`         | `16#5678_1234`         |
| `HIGH/LOW` | `2`    | `B A D C`         | `16#3412_7856`         |

```ladder
XIC(In_NewReading)SWPB(Raw_Register,HIGH/LOW,Reading)
```

An `INT` has only two bytes, so every order mode does the same thing to it: swaps them.
`16#1234` becomes `16#3412`. An `INT` source may go into a `DINT` destination. The swapped
`INT` keeps its sign there, so `16#12ab` becomes `16#ab12`, which as an `INT` is `-21742`, and
the `DINT` holds `-21742`. A `DINT` source cannot go into an `INT`: half its bytes would have
nowhere to go.

The source and the destination may be the same tag, so `SWPB(Word,HIGH/LOW,Word)` swaps a tag
in place. To swap a whole array of registers, swap each element in turn: Structured Text, with
a `FOR` loop, is the easier place for that.

## CLR — clear a word [#clr--clear-a-word]

`CLR` writes `0` into its destination. It is the fast way to zero a working register — shorter than `MOVE(0, dest)` and it reads as "clear this."

| Name   | Type                                |
| ------ | ----------------------------------- |
| `dest` | `DINT` \| `INT` \| `SINT` \| `REAL` |

```ladder
CLR(Wrk_Accumulator)
```

While the rung is true, `Wrk_Accumulator` becomes `0`. Unlike the other instructions here, `CLR` also accepts a `REAL` destination, which it clears to `0.0`.

## BTD — bit field distribute [#btd--bit-field-distribute]

`BTD` moves a **run of bits** from one position to another. It takes a `length`-bit field out of `source` starting at `sourceBit`, and lays it into `dest` starting at `destBit`. Every other bit of `dest` is left unchanged, and `source` itself is never modified.

| Name        | Type                      | Notes                                     |
| ----------- | ------------------------- | ----------------------------------------- |
| `source`    | `DINT` \| `INT` \| `SINT` | the bits to move                          |
| `sourceBit` | `DINT`                    | where the field starts in the source      |
| `dest`      | `DINT` \| `INT` \| `SINT` | where the field lands                     |
| `destBit`   | `DINT`                    | where the field starts in the destination |
| `length`    | `DINT`                    | 1–32, how many bits to move               |

`sourceBit`, `destBit`, and `length` are **immediate whole numbers** typed directly into the block — not tags.

A bit number cannot be larger than the tag it points into: a `DINT` has bits `0`–`31`, an `INT` has `0`–`15`, and a `SINT` has `0`–`7`. `sourceBit` is checked against the type of `source`, and `destBit` against the type of `dest`, so the two can differ in one instruction — moving a byte out of a `SINT` into bit 24 of a `DINT` is fine.

`length` is `1`–`32` and is **not** checked against the destination: a field that starts inside the destination and runs off the end is allowed, and the bits past the end are dropped.

```ladder
BTD(In_Packed,0,Out_Word,8,4)
```

This takes the lowest 4 bits of `In_Packed` and writes them into bits 8–11 of `Out_Word`, leaving the rest of `Out_Word` as it was. If the field would run off the top of the destination, the extra bits are simply dropped — they do **not** wrap around to bit 0, and they never reach a neighbouring tag.

## Common Mistakes [#common-mistakes]

- Using a `BOOL` operand on `AND` / `OR` / `XOR` / `NOT` / `BTD` — these are whole-word operations. Combine single bits with contacts and branches instead.
- Reaching for `NOT` to invert one contact — that is what `XIO` is for. `NOT` inverts all 32 bits of a word.
- Forgetting that `NOT` and `AND`-with-an-inverted-mask produce _negative_ `DINT` values when the high bit ends up set — the bit pattern is correct even though the decimal looks surprising.
- Writing `AND` / `OR` / `XOR` the wrong way around — the destination is the **last** operand.
- Typing a tag into `BTD`'s `sourceBit`, `destBit`, or `length` — those are fixed numbers, not tags. A bit position past the end of its own tag (`8` on a `SINT`, `16` on an `INT`, `32` on a `DINT`), or a length outside `1`–`32`, is a compile error.
- Choosing the wrong `SWPB` order mode. Compare the value you get with the one the device's manual shows: two letters swapped in each pair is `HIGH/LOW`, two halves swapped is `WORD`.
- Reaching for `CLR` on a `BOOL` — use an [`OTU`](https://rungs.dev/docs/ladder-logic/instructions/otl-otu) (unlatch) to drive a single bit to `0`. `CLR` zeroes a whole numeric word.

## Related [#related]

- [XIO](https://rungs.dev/docs/ladder-logic/instructions/xio) — invert a single bit on a rung (a normally-closed contact)
- [MOVE / MVM](https://rungs.dev/docs/ladder-logic/instructions/move) — copy a whole value, or copy only masked bits
- [Array Tags](https://rungs.dev/docs/tags/arrays) — a bitwise result is also legal inside an array subscript, e.g. `Buffer[Index AND 7]`
- [Logical Operators (Structured Text)](https://rungs.dev/docs/structured-text/logical-operators) — the same `AND` / `OR` / `XOR` / `NOT`, written as operators