The SCASX
instructions in x86 assembly language are powerful tools for scanning strings, enabling programmers to efficiently search for specific values within blocks of memory. The SCASX
family consists of scasb
, scasw
, scasd
, and scasq
, each designed to handle different data sizes: bytes, words, and doublewords respectively.
Understanding scasX
Instructions
The scasX
instructions are used to scan a string or array to find a specific value. They compare the value in the accumulator register (AL, AX, or EAX) with the value at the memory location pointed to by the Destination Index (DI) register. The comparison is performed on a byte, word, or doubleword basis, depending on the specific scasX
instruction used.
Variants of scasX
Instructions
scasb
(Scan String Byte):
- Compares the byte in
AL
with the byte at[DI]
. AL
is the 8-bit accumulator register.- Example:
scasb
scasw
(Scan String Word):
- Compares the word in
AX
with the word at[DI]
. AX
is the 16-bit accumulator register.- Example:
scasw
scasd
(Scan String Doubleword):
- Compares the doubleword in
EAX
with the doubleword at[DI]
. EAX
is the 32-bit accumulator register.- Example:
scasd
scasq
(Scan String Quadword):
- Compares the quadword in
RAX
with the quadword at[RDI]
. RAX
is the 64-bit accumulator register.- Example:
scasq
Syntax
The general syntax for scasX
instructions is as follows:
SCASB ; Scan byte string
SCASW ; Scan word string
SCASD ; Scan doubleword string
SCASQ : Scan quadword string
Instruction Operation
The general operation of scasX
instructions can be summarized as follows:
- The value in the accumulator register (
AL
,AX
,EAX
, orRAX
) is compared with the value at the memory address pointed to byDI
. - The Direction Flag (DF) determines whether the
DI
register is incremented or decremented after the comparison.- If DF is cleared (
cld
),DI
is incremented. - If DF is set (
std
),DI
is decremented.
- If DF is cleared (
- The result of the comparison affects the CPU flags (Zero Flag, Sign Flag, Carry Flag, etc.), which can be used for conditional branching.
Practical Usage
The scasX
instructions are often used in loops to search for a specific value in a string or array. Below are some practical examples demonstrating their usage.
Example 1: Searching for a Byte in a String
section .data
msg db 'Hello, World!', 0
section .text
org 0x7C00
start:
xor ax, ax
mov ss, ax
mov sp, 0x7C00
mov ax, 0x07C0
mov ds, ax
; Load the address of the string and the character to search for
mov di, msg
mov al, 'W'
mov cx, 13 ; Length of the string
; Clear the Direction Flag to increment DI
cld
search_loop:
repe scasb ; Repeat while CX is not zero and [DI] != AL
jz found ; Jump if zero flag is set (found the character)
not_found:
; Hang if not found
cli
hlt