r/asm • • Jan 18 '21

x86 How do I convert a decimal to binary??

Hey guys, I'm working on creating a decimal-to-binary converter and I can't seem to figure it out. I'd prefer for the number to be a double digit. Any ideas what might have gone wrong with my code? I need to get it done ASAP and I would really appreciate any kind of help .

---

.MODEL small

.stack 200h

DIS MACRO STR

MOV AH,09H

LEA DX,STR

INT 21H

ENDM

.model small

.stack 100h

.data

msg db 'Enter a decimal number:$'

number db 0 

.code

ProgramStart:

mov bx, u/data

mov ds,bx

mov dx,offset msg

mov ah,09

int 21H

CharRead:

mov ah,01H

int 21H

cmp al, 0DH

je FinishedNumber

sub al,30h

mov bl,al

mov al,number

mov cl,10

mul cl

add al,bl

mov number,al

jmp CharRead

FinishedNumber:

;binary conversion

and al,0fh ;first 4 bits are set to 0

mov cl,3 ;cl used as counter

mov bl,al

mov bh,bl

shr bh,cl ;shift right three times

add bh,30h ;make binary value visible as 0 or 1

mov ah,2 ;print binary value

mov dl,bh

int 21h

xor bh,bh ;clear bh register

mov bh,bl

mov cl,2 ;counter=2

and bh,04h ;deletes all bits except the last third

shr bh,cl

add bh,30h

mov ah,2 ;print last three bit

mov dl,bh

int 21h

xor bh,bh

mov bh,bl

and bh,02h ;deletes all bits except the second last bit

shr bh,1

add bh,30h

mov ah,2 ;prints

mov dl,bh

int 21h

xor bh,bh

mov bh,bl

and bh,01h ;deletes all except the last one

add bh,30h

mov ah,2 ;prints

mov dl,bh

int 21h

jmp exit 

exit:

mov   ah,2     ;prints the number in binary 

mov dl,bh

int 21h

mov ah,4ch

int 21h

end ProgramStart

0 Upvotes

7 comments sorted by

40

u/the_Demongod Jan 18 '21

To begin with, this is ridiculously hard to read. Apply block code formatting to everything and comment what you have already so that it's comprehendible to someone with zero context, or you're not going to get any help.

14

u/PE1NUT Jan 18 '21

Generally a good idea to start with stating which CPU you are trying to get to run this on, and which particular assembler you're using, as they can have different notations.

5

u/Spire Jan 18 '21

I agree.

If I had to guess, I'd say this looks like MASM under MS-DOS (x86).

-1

u/Dillinur Jan 18 '21

Just post the binary at this point lol

9

u/Poddster Jan 18 '21
  1. Can you do it on paper?

  2. What's wrong with your current code? What do you think needs to change?

5

u/tobiasvl Jan 18 '21

So what's wrong with it? What does it do?

1

u/oh5nxo Jan 19 '21

Consider another way: push 0 to mark end. Extract the bits lsbit first, pushing each character instead of printing. When your number becomes zero, pop out and print the characters.