6.5 String Instructions and Prefixes
In 8086 terminology, a string is a consecutive sequence of bytes or words. It may contain text, numbers, pixels, or any other data. String instructions save encoding space by using implicit operands: the mnemonic does not list every register, but the hardware follows fixed rules.
One string instruction processes one element
The byte forms advance pointers by 1; word forms advance them by 2:
MOVSB/MOVSWcopy from DS:[SI] to ES:[DI].
LODSB/LODSWload DS:[SI] into AL or AX.
STOSB/STOSWstore AL or AX into ES:[DI].
CMPSB/CMPSWcompare DS:[SI] with ES:[DI] and set flags like subtraction.
SCASB/SCASWcompare AL or AX with ES:[DI] and set flags.
The direction flag (DF) determines pointer movement after the element:
- DF=0 means forward: SI and/or DI increase.
CLDclears DF.
- DF=1 means backward: SI and/or DI decrease.
STDsets DF.
Example: DS:[SI] contains 34H, ES:[DI] contains 00H, and DF=0. One MOVSB writes 34H to ES:[DI], then increments both SI and DI. It does not change CX by itself.
For the original 8086 string destination, ES is fixed. A segment-override prefix may replace the default DS used by the source, but it does not redirect the ES destination. Procedures should normally execute CLD before forward string processing unless their calling convention already guarantees DF=0.
REP prefixes add hardware-controlled repetition
A repeat prefix makes the CPU execute one string instruction repeatedly while decrementing CX after every element:
REPrepeats MOVS, LODS, or STOS until CX becomes zero.
REPE/REPZrepeats CMPS or SCAS while CX is nonzero and the latest comparison has ZF=1.
REPNE/REPNZrepeats CMPS or SCAS while CX is nonzero and the latest comparison has ZF=0.
CX=0 at entry means zero iterations. Unlike the LOOP instruction’s zero-count hazard, a repeat prefix checks the count before processing an element.
Suppose two five-byte arrays first differ at index 2. REPE CMPSB compares indices 0 and 1 successfully, then compares index 2 and clears ZF. It stops after three iterations with CX=2; SI and DI already point one element beyond the mismatch.
To find byte 7EH, place it in AL, point ES:DI at the search range, load CX with the maximum length, clear DF for forward scanning, and execute REPNE SCASB. A stop with ZF=1 means a match was found. A stop with CX=0 and ZF=0 means the range was exhausted without a match. Because DI advances after the successful comparison, the matching byte is at DI−1 in a forward scan.
Chapter 6 has turned encoded operands into working programs: data can move, arithmetic and logic can transform it, flags can steer control, and string prefixes can process whole regions. Chapter 7 will combine these instructions into complete assembly-language program structures.