2

So I'm building a simple 8086 Assembly program that allows the user to input 4 digits, store them in an array and print out the sum of those digits (The sum must be a one digit number):

data segment

    i db ?
    array db 20 dup(?)
    sum db ?

ends

stack segment

    dw 128 dup(0)

ends

code segment

    mov ax, data
    mov ds, ax
    mov es, ax

    mov i, 0

Enter:
    mov ah, 1
    int 21h
    mov bl, i
    mov bh, 0

    mov array[bx], al

    inc i
    cmp i, 4
    jne Enter

    mov sum, 0
    mov i, 0

Calc:
    mov bl, i
    mov bh, 0
    mov al, array[bx]

    add sum, al

    inc i
    cmp i, 4
    jne Calc

    mov dl, sum
    mov ah, 2
    int 21h

    mov ax, 4c00h
    int 21h

ends

However when I input the numbers 1 1 2 5 instead of giving me 9 it gives me some random character.

Any ideas?

Fifoernik
  • 9,779
  • 1
  • 21
  • 27
David Daniels
  • 131
  • 1
  • 7

1 Answers1

3

The DOS character input function gives you characters.
When you key in 1 DOS presents you with AL='1' meaning you get 49 where you might expect 1.
When you key in 2 DOS presents you with AL='2' meaning you get 50 where you might expect 2.
When you key in 5 DOS presents you with AL='5' meaning you get 53 where you might expect 5.
That's why we subtract 48 in these cases.

Enter:
    mov ah, 1
    int 21h
    mov bl, i
    mov bh, 0
    SUB AL, '0'        ;Same as SUB AL, 48
    mov array[bx], al

This way your array will contain the values 1, 1, 2, and 5 (No longer the characters '1', '1', '2', and '5')

Now you can safely do the additions, yielding 9.

Because sum now holds the value 9, but you need the character '9', you simple add 48 to do the conversion:

    mov dl, sum
    ADD DL, '0'        ;Same as ADD DL, 48
    mov ah, 02h
    int 21h
Sep Roland
  • 33,889
  • 7
  • 43
  • 76