TheLiquor
TheLiquor

Reputation: 71

Negative Numbers MASM Input and Output

I am in the process of writing a byte sized poly derivative app in MASM x8086 and it has to be able to receive negative coefficients.

I understand that binary can be represented in signed and unsigned form. But I am looking for a way to receive a signed integer so that I can avoid another array. Or is there a way to define my variable as a signed integer?

Below is my integer input procedure.

TEN db 10  ;;; constant
num db ?   ;;; coefficient
           ;;; bh is the degree

get_int PROC
  lea si, string     ; replaces the ? in the string with the degree
  add si, 13h
  mov dl, bh
  add dl, 30h
  mov [si], dl

  mov ah, 09h
  lea dx, string     ; prompt
  int 21h

  mov ah, 0Ah
  lea dx, buffString ; user input
  int 21h

  lea si, buffString ; point to count byte
  inc si

  mov ch, 00h        ; cx = count
  mov cl, [si]

  add si, cx         ; si points to end of string

  mov dl, 00h        ; hold result(dl)
  mov bl, 01h        ; hold 10^x (bl)

loop1:
  mov al, [si]       ; prep for char ---> number conversion
  cmp al, '-'
  je negativeSign

  sub al, 30h        ; convert
  mul bl             ; ax = al*bl
  add dl, al         ; sum of results

  mov al, bl         ; preload for instruction
  mul TEN            ; TEN is variable predefined as 10
  mov bl, al
  jmp overNegative
negativeSign:

  mov dh, 00h
  mov [si], dh
overNegative: 
  dec si
  loop loop1         ; loop instruction uses cx as index counter once zero breaks

  mov num, dl
  ret 
get_int ENDP
; output is num

Upvotes: 0

Views: 1995

Answers (1)

Fifoernik
Fifoernik

Reputation: 9899

When, while interpreting the input, you stumble upon the "-" character it is a save assumption that you reached the start of the number. Therefore you should bail out of the loop. I don't see any point in replacing the "-" character by a zero!

What you do need to do is negate the number to obtain the correct signed result:

loop1:
 mov al, [si]       ; prep for char ---> number conversion
 cmp al, '-'
 je negativeSign

 sub al, 30h        ; convert
 mul bl             ; ax = al*bl
 add dl, al         ; sum of results

 mov al, bl         ; preload for instruction
 mul TEN            ; TEN is variable predefined as 10
 mov bl, al
 dec si
 loop loop1         ; loop instruction uses cx as index counter once zero breaks

 mov num, dl        ;Positive number [0,127]
 ret 

negativeSign:
 mov dh, 00h        <<<<<<< Need this as a flag?
 neg dl
 mov num, dl        ;Negative number [-128,-1]
 ret

Upvotes: 1

Related Questions