Source code:
org 100h
.data
buffer db 7, 0, 7 dup(0) ; DOS input buffer
prompt db 'Enter number: $'
binary_label db 13,10,'Binary: $'
newline db 13,10,'$'
.code
start:
; Print prompt
mov ah, 09h
lea dx, prompt
int 21h
; Get input string
lea dx, buffer
mov ah, 0Ah
int 21h
; Pointer to input chars (after size & count bytes)
lea si, buffer + 2
; Check if input is exactly '0' and Enter -> exit program
mov al, [si]
cmp al, '0'
jne convert_input
cmp byte ptr [si + 1], 13
je exit_program
convert_input:
call str_to_num ; AX = signed number
; Truncate to 8 bits (signed)
mov bl, al
; Print newline and "Binary: "
mov ah, 09h
lea dx, binary_label
int 21h
; Print 8-bit binary of BL
mov cx, 8 ; 8 bits to print
print_loop:
shl bl, 1 ; shift left, MSB -> CF
jc print_one
mov dl, '0'
jmp display_bit
print_one:
mov dl, '1'
display_bit:
mov ah, 02h
int 21h
loop print_loop
; Print newline
mov ah, 09h
lea dx, newline
int 21h
jmp start
; -------------------------
; Convert string to signed number in AX
; Supports negative sign
; -------------------------
str_to_num:
xor ax, ax ; Clear AX (result)
xor bx, bx ; Clear BX (temp)
xor cx, cx ; digit holder
mov di, 0 ; sign flag (0=+, 1=-)
lea si, buffer + 2
; Check for negative sign
mov al, [si]
cmp al, '-'
jne parse_loop
mov di, 1 ; negative
inc si ; skip '-'
parse_loop:
mov al, [si]
cmp al, 13 ; Enter key = end
je done_parse
sub al, '0' ; ASCII to digit
cmp al, 9 ; sanity check digit 0-9
ja invalid_input
mov cx, ax
mov ax, bx
mov dx, 0
mov bx, 10
mul bx ; AX*10
add ax, cx ; add digit
mov bx, ax
inc si
jmp parse_loop
done_parse:
mov ax, bx
cmp di, 1
jne finish_convert
neg ax
finish_convert:
ret
invalid_input:
; On invalid input, return 0
xor ax, ax
ret
exit_program:
mov ah, 4Ch
int 21h
Essay:
The program begins by prompting the user to enter a number, which it reads as a string and
then converts into a signed integer. This conversion happens in the `str_to_num` routine, where
each character is processed by subtracting the ASCII offset to get its digit value and then
building the number through repeated multiplication and addition. A status flag stored in the `di`
register indicates whether the number is negative; if so, the `NEG` instruction is used to convert
the number to its signed form. Input is captured using DOS interrupt 21h, function 0Ah, where
the first two bytes of the buffer define its size and the number of characters read. The binary
representation is generated by repeatedly shifting bits in the `BL` register and using the Carry
Flag (CF) to determine each bit's value. The process repeats until the user inputs '0' followed by
Enter, which triggers the program to terminate.