0

I'm a begginer in emu8086 and I have a problem with this code that I dont seem to be able to fix. I need to convert from decimal to binary and sometimes it does it great, for example, when I use numbers like 4,8,15,16,255 everything works fine. But if I use for example, 2,9,17,254 it doesn´t show the right number. I really need help with this.

.model small

.data

exp db 8 dup (?)

num dw 09

var dw 2

.code

start:
    mov ax,@data
    mov ds,ax 

    mov di,0 
    mov ax,num ;I put my number in ax

    Binary: ;Here I make the conversion from decimal to binary
        div var
        mov exp[di],dl
        inc di 
        cmp al,0 ;If my number is equal to 0 it breaks the cicle and shows the array in the next function
        ja Binary


    dec di    
    mov cx,di        
    Show:   ;Here I show the array backwards so we can see the real binary number  
        mov bl,exp[di] 
        add bl,30h

        mov dl,bl 
        sub bl,30h 

        mov ah,2
        int 21h    
        dec di
    loop Show

int 21h    
end start:

end

  • Don't use `div` to divide by 2! It's about 30x slower than a shift, and it can't take an immediate operand. https://stackoverflow.com/questions/40354978/why-is-this-c-code-faster-than-my-hand-written-assembly-for-testing-the-collat/40355466#40355466 – Peter Cordes Oct 19 '17 at 07:18

1 Answers1

1

div var divides dx:ax by var. You need to zero dx before the divide instruction.

prl
  • 11,716
  • 2
  • 13
  • 31
  • There's a canonical Q&A for failure to zero or sign extend into [e]dx:[e]ax before div or idiv that makes a pretty good dup target. (There's a link in the [x86 tag wiki](https://stackoverflow.com/tags/x86/info), just search for `div`). – Peter Cordes Oct 19 '17 at 07:21