Accepting a string and displaying its length in assembly

Viewed 139
print macro msg
lea dx, msg
mov ah, 09h
int 21h
endm

data segment
msg1        db  13, 10, 10, 'Enter the string: $'
msg2        db  13, 10, 10, 'The entered string is: $'
msg3        db  13, 10, 10, 'The length of the string is: $'
array       db  20 dup(0)
lenstr      db  5   dup(0)
data ends

code segment
assume cs: code, ds: data
start:      mov ax, data
    mov ds, ax
    
    print msg1
    lea si, array

This is an ALP to accept a string from the keyboard and display its length. There are various parts where I don't understand how the program works.

read:       mov ah, 01h
int 21h
cmp al, 0dh
je next
mov [si], al
inc si
inc bl
jmp read

Here, why are we comparing al, 0dh, when al does not contain any value to begin with?
So, it will be really helpful if someone could explain the whole program.

next:       mov al, '$'
mov [si], al
print msg2
print array
print msg3
lea si, lenstr

xor ax, ax
mov al, bl
mov bl, 10
div bl
add al, 30h
mov [si], al
inc di
add ah, 30h
mov [si], ah
inc si
mov al, '$'
mov [si], al
print lenstr
mov ax, 4c00h
int 21h
code ends
end start

Also, can't we just use count db $-array to find the length of the string?

1 Answers
read: mov ah, 01h  ; Identification of DOS service.
int 21h            ; Invokation of the service.  
cmp al, 0dh
je next
mov [si], al
inc si
inc bl
jmp read

DOS service Int 21h/AH=01h waits until user has pressed a key, for instance the digit 5, and it returns AL=35h in this case. When s|he pressed Enter (which signalizes end of string), service returns AL=0Dh.

why are we comparing al,0dh, when al does not contain any value to begin with?

You'd better ask why are we incrementing bl when we don't know what was in it before? We cannot rely that registers contain 0 at the start of our program (thou some of them do). Apparently bl is intended to count the number of entered characters.

Also, can't we just use count db $-array to find the length of the string?

Only if the string is defined statically in the program. We don't know how many character is the user going to type, so we have to count them dynamically on the run.
Inserting $ after the last entered character is required by DOS service Int 21h/AH=09h which is employed in macro print.

Related