Reputation: 20
I'm trying to convert a string I read with this code to binary and hexa.
READ_STRING:
MOV DX, offset buffer
MOV AH, 0Ah
INT 21h
MOV SI, 1d
MOV AX, 0
XOR CX, CX
MOV CL, buffer[SI]
INC SI
LOOP_1:
MOV DX, 10
MUL DX
MOV DL, buffer[SI]
SUB DL, 30h
MOV DH, 0
ADD AX, DX
INC SI
LOOP LOOP_1
RET
So far I have this code for binary output but it always prints "1001" (9 in decimal):
NEXT:
XOR AX, AX
XOR BX, BX
XOR CX, CX
MOV CL, 2
MOV AL, byte ptr[nombre]
MOV DI, offset binaire
; DIV : divide AX by CL. Remainder in AH and result in AL
LOOP:
DIV CL ; remainder in AH, quotient in AL
ADD AH, '0' ; 0 -> '0' , 1 -> '1'
MOV [DI], AH ; Saves the remainder in the array
INC DI
MOV AH, 0 ; reset AH for next division
CMP AL, 0 ; if result is 0, end
JNE LOOP
;Prints the binary number
MOV DX, offset binaire
CALL WRITE_STRING
Thanks! If you need anything else just ask.
Upvotes: 0
Views: 14213
Reputation: 37262
Before worrying about whether or not you can display the value as binary or hexadecimal; check to make sure your code correctly converts the user's input into an integer (e.g. with a debugger).
For binary, consider something like this:
mov bx,ax ;bx = the value to display as binary
mov cx,16 ;cx = number of bits to display
mov di,offset binaire ;es:di = address to store string
.nextBit:
xor ax,ax ;al = 0
add bx,bx ;bx = value * 2; carry flag = overflow
adc al,0 ;al = '0' or '1'
stosb ;Add new character to string
loop .nextBit
mov byte [di],0 ;Terminate the string (ASCIIZ?)
mov dx, offset binaire
call WRITE_STRING
For hexadecimal, it's the same basic idea, except you need to extract the highest 4 bits:
mov bx,ax ;bx = the value to display as binary
mov cx,4 ;cx = number of nibbles to display
mov di,offset binaire ;es:di = address to store string
.nextNibble:
mov ax,bx ;ax = value
shr ax,12 ;ax = highest 4 bits of value
shl bx,4 ;bx = value << 4
add al,'0'
cmp al,'9'
jbe .gotChar
add al,'A' - '9'
.gotChar:
stosb ;Add new character to string
loop .nextBit
mov byte [di],0 ;Terminate the string (ASCIIZ?)
mov dx, offset binaire
call WRITE_STRING
Note 1: I haven't tested any of the code above, and I normally use NASM (not MASM), so it may not assemble "as is".
Note 2: Example code above is intentionally simple. For performance you could do a lot better using lookup tables instead.
Note 3: These aren't complex algorithms and you shouldn't need to mess about with high level languages first (unless you don't understand the theory/maths behind binary/hex conversion perhaps). Also, an algorithm that seems elegant in one language can be an ugly mess in another language (e.g. you can't detect overflow in an easy/clean way in C, so the method used for binary conversion above wouldn't be obvious or elegant in C; and a different method that is elegant in C might suck badly in assembly).
Upvotes: 2