Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- .8086
- .MODEL TINY
- _CODE SEGMENT PARA PUBLIC 'CODE'
- ASSUME CS:_CODE, DS:_CODE
- ORG 100h
- _start:
- ;Ask for the first number
- mov si, offset strPrompt1
- call readNumber
- ;Keep it
- mov bx, ax
- ;Ask for the second number
- mov si, offset strPrompt2
- call readNumber
- ;Add the number (check for overflow)
- add bx, ax
- jnc _print
- ;Overflow
- mov ah, 09h
- mov dx, OFFSET strResultTooBig
- int 21h
- jmp _end
- _print:
- ;Print the number
- mov ah, 09h
- mov dx, OFFSET strResult
- int 21h
- mov si, bx
- call printNumber
- mov ah, 09h
- mov dx, OFFSET strCRLF
- int 21h
- _end:
- mov ax, 4c00h
- int 21h
- ;;
- ;; FUNCTIONS
- ;;
- ;si = number
- printNumber:
- push ax
- push bx
- push dx
- ;Divisor
- mov bx, 10000
- mov ax, si
- ;Print zeros flag
- xor si, si
- printNum_loop:
- ;Find the current digit
- xor dx, dx
- div bx
- ;If non-zero or the flag is set, print the digit
- or si, ax
- jnz printNum_print
- ;If it's the last digit print it anyway
- cmp bx, 1
- jnz printNum_next
- printNum_print:
- push dx
- mov dl, al
- add dl, 30h
- mov ah, 02h
- int 21h
- pop dx
- printNum_next:
- ;Divide the divisor by 10
- push dx
- mov ax, bx
- xor dx, dx
- mov bx, 10
- div bx
- mov bx, ax
- pop dx
- ;The rest is the new number
- mov ax, dx
- ;Printed all the digits?
- cmp bx, 0
- jne printNum_loop
- pop dx
- pop bx
- pop ax
- ret
- ;si = ptr number
- convertNumber:
- push bx
- push cx
- ;Accumulator = 0
- xor bx, bx
- cvtNum_loop:
- ;Read a char
- xor ax, ax
- lodsb
- ;End of the string?
- cmp al, 0dh
- je cvtNum_end
- ;Invalid digit?
- cmp al, '0'
- jb cvtNum_prologue
- cmp al, '9'
- ja cvtNum_invalid
- ;Digital to digit
- sub al, '0'
- ;Multiply the accumulator by 10
- mov cx, bx
- shl cx, 1
- jc cvtNum_prologue
- shl bx, 1
- jc cvtNum_prologue
- shl bx, 1
- jc cvtNum_prologue
- shl bx, 1
- jc cvtNum_prologue
- add bx, cx
- jc cvtNum_prologue
- add bx, ax
- jmp cvtNum_loop
- cvtNum_invalid:
- ;Set the CF
- mov ax, 8000h
- shl ax, 1
- jmp cvtNum_prologue
- cvtNum_end:
- mov ax, bx
- xor bx, bx
- cvtNum_prologue:
- pop cx
- pop bx
- ret
- ;si = prompt
- readNumber:
- push dx
- mov ah, 09h
- mov dx, si
- int 21h
- mov BYTE PTR [inputBuffer+1], 0
- mov ah, 0ah
- mov dx, OFFSET inputBuffer
- int 21h
- push si
- mov si, OFFSET inputBuffer + 2
- call convertNumber
- pop si
- jnc readNum_end
- mov ah, 09h
- mov dx, OFFSET strOverflow
- int 21h
- pop dx
- jmp readNumber
- readNum_end:
- pop dx
- ret
- ;;
- ;; DATA
- ;;
- inputBuffer db 7, 0, 7 DUP(0)
- strPrompt1 db "Insert the first number: ", 24h
- strPrompt2 db 0dh, 0ah, "Insert the second number: ", 24h
- strOverflow db 0d, 0ah, "The number is too big or invalid.", 0dh, 0ah, 24h
- strResultTooBig db 0dh, 0ah, "The result is too big.", 0dh, 0ah, 24h
- strResult db 0dh, 0ah, "The result is: ", 24h
- strCRLF db 0dh, 0ah, 24h
- _CODE ENDS
- END _start
Advertisement
Add Comment
Please, Sign In to add comment