MOULDLKnowledge BaseElectrical Knowledge Base3D Model DownloadsMembership
中文版Model Store »
Knowledge Base › Electrical Knowledge Base › How do you shift and concatenate multi-word data in a function call (FC)?
HomeModels
Table of contents

On this page

PLC & Programming (100 articles)

Quick Reference

  • PLC & Programming
  • Electrical & Electronic Basics (monthly)(每月更新中)
  • Electrical Control & Drawings (monthly)(每月更新中)
  • Drives & Actuators (monthly)(每月更新中)
  • Sensors & Detection (monthly)(每月更新中)
  • Industrial Communication & Networks (monthly)(每月更新中)
  • HMI & Host Systems (monthly)(每月更新中)
  • Industrial Robots & Motion Control (monthly)(每月更新中)
  • Mechatronic System Integration (monthly)(每月更新中)
  • Fault Diagnosis & Standards (monthly)(每月更新中)

How do you shift and concatenate multi-word data in a function call (FC)?

Message packing, encoder data merging, high/low word swaps — all come down to "shift and concatenate". Such pure calculation is stateless with same-in-same-out behaviour: exactly an FC's job. This article gives the standard patterns (building a double word, splitting halves, extracting segments, BCD conversion) as copy-ready templates.

1. Two 16-bit words into one 32-bit value

High word Dw_H and low word Dw_L combine into a double word:

DINT result = (DINT)high × 65536 + (DINT)low    (or: double = high shifted left 16 OR low)

Ladder form: assign the double word whole with DMOV-type instructions, or write the halves separately (many platforms allow writing the high/low halves of a double word, e.g. Mitsubishi D0 and D1 as the two halves). One caution: treat the low word as unsigned when concatenating — if the low word is interpreted signed (negative), direct addition corrupts the result. Mask the low word with AND 0xFFFF before joining. The double's sign comes from the high word's sign bit; never sign-extend the low word.

2. Splitting: halves and arbitrary bit segments

GoalMethodNote
Take the high 16 bitsShift the double right 16 and take the low word (or read the high half directly)Reading the half-word is most direct
Take the low 16 bitsDouble AND 0xFFFFMasked extraction
Take any segmentAND mask → SHR into placeMask first, then shift — value right-aligned
Replace a segmentAND NOT mask to clear → OR the shifted-in new valueClear then set — both steps required

"Mask first, then shift" — memorise the order: extracting = AND the mask, then shift right to bit 0; replacing = clear the segment in the target, then OR in the new value. Reversed, the segment lands skewed and the debugging is miserable.

3. Shift type traps: signed and rotate

Three classic mistakes: ① arithmetic right shift of a signed (negative) value fills sign bits — unsigned data must not be shifted as signed; ② left shift is not always ×2: overflowed bits vanish, so a status word (bits with meaning) destroyed by a left shift is a data-semantic error, not arithmetic; ③ rotate (ROL/ROR) and shift (SHL/SHR) serve different purposes: message rotation uses rotate, numeric scaling uses shift — mixing them is a semantic error.

NeedWhichWhy
Value ×2 / ÷2SHL / SHROverflow handled by numeric semantics
Rotating a status wordROL / RORNo bits lost, positions change only
Extract a segmentSHR + ANDMask first, then shift
Sign extensionPlatform instructionHand-rolled versions err easily

4. BCD and hexadecimal conversion

Instruments and thumbwheel switches commonly emit BCD (one decimal digit per 4 bits). Wrap conversions in an FC: BCD → integer = extract each nibble (AND 0xF, SHR 4) and weight it (units ×1, tens ×10, hundreds ×100); integer → BCD reverses by divide-and-remainder into nibbles. Most platforms have built-in BCD instructions (BIN/BCD converts) — prefer them; the self-written FC's value is "with range checking": a nibble above 9 raises an error, keeping sick instrument data out of the program.

5. A message-packing template

Message fieldSourcePacking action
HeaderConstant 0xAA55MOV into the first word
Status bitsVarious M flagsOR each into the status word
MeasurementFloat 12.3 mm×10, round to 123, write (or per protocol scaling)
Serial double wordD100 (double)High/low words written to the two message words
ChecksumSum of all preceding bytesFOR-loop accumulate, AND 0xFF

The packing FC's input is "the data area to pack", its output "the message buffer" — read and write areas separated (pure-function discipline), so main and comms tasks may both call it safely. Do the scaling (×10, ×100) uniformly at packing, with the protocol's scaling factors written into the FC comments.

6. Common errors

SymptomCauseFix
Assembled double word jumps aroundLow word not masked for signAND 0xFFFF before joining
Extracted segment skewedShift before mask, order reversedMask first, then shift
Negative values shift into nonsenseUnsigned data shifted as signedUnsigned type or dedicated instructions
Checksum always wrongByte order (endianness) mismatches the protocolAdjust word order per protocol, verify with a capture
BCD conversion occasionally garbledNo nibble validationNibble > 9 raises an error

7. Notes

The whole shift-and-concatenate craft compresses to three sentences: build = shift up (or weight) and add, masking the low word; split = mask first, then shift; replace = clear the segment, then set it. Write a pure-function FC five-pack (build / split / extract / replace / BCD) into the company library and bit-level data work never gets hand-rolled again.

8. References

Shift/rotate/word-double-word instruction syntax follows the PLC's programming manual applied-instruction chapters (SHL/SHR/ROL/ROR/DMOV etc.); byte order and scaling follow the communication protocol documents; BCD instruction behaviour follows the manuals; communication data handling does not alter safety-function independence per GB 5226.1 / IEC 60204-1.

9. Cautions

⚠️ Three traps to avoid:
① Unmasked low word signed-extended into the double — negatives sneak into results occasionally;
② Endianness never reconciled with the protocol — data right, "positions all wrong";
③ Shifts used as universal multiply/divide — overflow silently destroys status words.

For every new protocol, write a "scaling table" first: each field's type, byte order and scaling factor; the packing FC follows the table — table right, message right.

Related reading

Related 3D models: Ready to build it? Download free 3D models & CAD drawings at MOULDL »
MOULDL · Electrical Knowledge Base · free self-study reference for electrical & automation engineers, 3D CAD models at MOULDL