The SCASB/SCASW instructions

Compare memory with the AL or AX register.

The SCASB/SCASW instruction format

InstructionDescription
SCASBCompare AL with the byte at ES:DI, then set the status flags.
SCASWCompare AX with the word at ES:DI, then set the status flags.

This instruction compares the byte or word defined by the memory operand with the value in the al or ax. It then sets the status flags in EFLAGS that record the results. The address of the memory operand is read from the es:di. Note that es cannot be overridden by a segment override prefix.

After the comparison, the di register is automatically incremented or decremented according to the setting of the DF flag in the FLAGS register. If the DF flag is 0, the di register is incremented; if the DF flag is 1, the di register is decremented. The register is incremented or decremented by 1 for byte operations and by 2 for word operations.

Usage example: searching for a character in a string

title Author: Evgeny Sergeevich Dovgopolov

.model small
.stack 100h

data segment public
    string db  "Hello World!"
    strlen equ ($-string)
data ends

code segment public              ; Start of the code segment
    assume ds:data, cs:code

    main proc                    ; Start of the main procedure
        mov     ax, seg data     ; Get the data segment address and store it in the ax register
        mov     ds, ax           ; Pass the data segment address from ax to ds
        mov     es, ax           ; Pass the data segment address from ax to es

        mov     cx, strlen       ; Set the counter equal to the length of the string
        lea     di, es:[string]  ; Load the address of the variable string into es:di

        mov     al, 'W'          ; Copy the value 'W' into the al register

  repnz scasb                    ; Search for the character 'W' at es:di while CX≠0 or the ZF flag≠0
        jnz     NotFound         ; If ZF=0, jump to the NotFound label

        dec     di               ; Decrease di by 1 so that it points to the found element
        mov     ax, di           ; Copy the value of di into the ax register
        jmp     Done             ; Jump unconditionally to the Done label

    NotFound:
        mov     ax, 0FFFFh       ; Copy the value -1 into the ax register

    Done:
        mov     ax, 4C00h        ; Copy the process termination function number into ah and the value into al
        int     21h              ; Call the interrupt
    main endp                    ; End of the main procedure

code ends                        ; End of the code segment
end main                         ; End of file. The main procedure is the entry point

Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".

Processor status flags

CF
Yes
PF
Yes
AF
Yes
ZF
Yes
SF
Yes
TF
No
IF
No
DF
No
OF
Yes

Note: the DF flag is not changed by the SCASB/SCASW instructions, but it affects the direction of processing (incrementing/decrementing the index).