Finding numbers in a string and computing their sum
A program that extracts numbers from a string and computes their sum.
Program source code
title .model small .stack 100h data segment public string db "I was born in 1988, March 17$" data ends code segment public assume ds:data, cs:code main proc mov ax, seg data ; Get the data segment address and store it in ax mov ds, ax ; Pass the data segment address from ax to ds lea si, ds:[string] ; Load the address of the string variable into the ds:si register call FindNumber ; Call the FindNumber procedure mov ax, 4C00h ; Copy the termination function number into ah and the value into al int 21h ; Call the interrupt main endp FindNumber proc xor ax, ax ; Clear the value of the ax register xor bx, bx ; Clear the value of the bx register FindLoop: lodsb ; Load a byte from the si register into the al register cmp al, 24h ; Compare the value in the al register with 24h - '$' je Finish ; If ZF=1, then jump to the label Finish cmp al, 31h ; Compare the value in the al register with the ASCII value 1 jb FindLoop ; If the value in al is below 1, then jump to the label FindLoop cmp al, 39h ; Compare the value in the al register with the ASCII value 9 ja FindLoop ; If the value in al is above 9, then jump to the label FindLoop and al, 0Fh ; Apply a mask that clears the high nibble of the al register add bx, ax ; Add the value in the ax register to the value in the bx register jmp FindLoop ; Jump unconditionally to the FindLoop label Finish: test bx, bx ; Check the value of the bx register for 0 jnz HasNumbers ; If ZF=0, then jump to the label HasNumbers mov ah, 02h ; Copy the console output function number into ah mov dl, 30h ; Copy the ASCII value 0 into the dl register int 21h ; Call the interrupt jmp Done ; Jump unconditionally to the Done label HasNumbers: xchg ax, bx ; Exchange the contents of the ax and bx registers aam ; Create a pair of unpacked BCD values (base 10) or ax, 3030h ; Convert the value in the ax register to an ASCII number xchg ax, bx ; Exchange the contents of the ax and bx registers mov ah, 02h ; Copy the console output function number into ah cmp bh, 30h ; Compare the value in the bh register with the ASCII value 0 jz PrintOneNumber ; If ZF=1, then jump to the label PrintOneNumber mov dl, bh ; Copy the value of the bh register into the dl register int 21h ; Call the interrupt PrintOneNumber: mov dl, bl ; Copy the value of the bl register into the dl register int 21h ; Call the interrupt Done: ret ; Return from the procedure FindNumber endp code ends end main
34
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".