Tuesday, January 19, 2010

CS401

; Searching a substring from a Main string
[org 0x0100]
jmp start

mstr: db 'aaab', 0
sstr: db 'aab', 0
sub_len: dw ; Used to contain length of sub string
start: dw ; Place to resume search
stop: dw ; Last place to begin search

; subroutine to calculate the length of a string
; takes the segment and offset of a string as parameters
strlen: push bp
mov bp,sp
push es
push cx
push di
les di, [bp+4] ; point es:di to string
mov cx, 0xffff ; load maximum number in cx
xor al, al ; load a zero in al
repne scasb ; find zero in the string
mov ax, 0xffff ; load maximum number in ax
sub ax, cx ; find change in cx
dec ax ; exclude null from length
pop di
pop cx
pop es
pop bp
ret 4

; subroutine to compare two strings
; takes segment and offset pairs of two strings to compare
; returns 1 in ax if they match and 0 other wise
strcmp: push bp
mov bp,sp
push cx
push si
push di
push es
push ds

lds si, [bp+4] ; point ds:si to first sstr
les di, [bp+8] ; point es:di to second mstr

push es ; push segment of mstr
push di ; push offset of mstr
call strlen ; calculate string length
mov bx, ax ; save length in bx

push ds ; push segment of sstr
push si ; push offset of sstr
call strlen ; calculate string length
; Now length of sstr is in ax register
; See if mstr/sstr are null or sstr longer than mstr

or bx,bx ; mstr null?
JE exitfalse
cmp ax,0 ; sstr null?
JE exitfalse
cmp ax, bx ; sstr>mstr?
JE exitfalse

mov sub_len, ax ; Move length of sstr in sub_len

; see if the sstr is substring of mstr

LEA SI, sstr ; SI points to sstr
LEA DI, mstr ; DI points to mstr
Cld ; Left to right processing

; Compute STOP

mov stop, DI ; stop has mstr address
add stop, bx
mov cx,sub_len
sub stop,cx ; subtract substring length

; Initialize start

mov start, DI
REPEAT:
; compare characters
mov cx, sub_len
mov DI, start ; reset DI
LEA SI, sstr ; reset SI
Repe cmpsb ; compare characters

JE exitsimple

; substring not found yet

INC start
; see if the start<=stop

mov ax, start
cmp ax, stop
JNLE exitfalse
JMP REPEAT
mov ax,1
JMP exitsimple

exitfalse: mov ax, 0 ; store 0 to mark unequal

exitsimple: pop ds
pop es
pop di
pop si
pop cx
pop bp
ret 8

start: push ds ; push segment of first string
mov ax, mstr
push ax ; push offset of first string
push ds ; push segment of second string
mov ax, sstr
push ax ; push offset of second string
call strcmp ; call strcmp subroutine

mov ax, 0x4c00 ; terminate program
int 0x21

No comments: