Chapter 9.2: The emu8086.inc Library

Microprocessors
The INCLUDE directiveMacrosPUTC · GOTOXYPRINT · PRINTNCursor macrosProceduresReading / printing numbersPTHIS and the stackExample programs
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

INCLUDE

Explain how a library file is pulled into the source and where the assembler looks for it.

Macros

Show what macros such as PUTC, GOTOXY, PRINT and PRINTN expand to.

Procedures

Use the ready-made procedures (number input/output, string printing) with DEFINE_… and CALL.

Example programs

Write programs that read numbers, compute with them and lay out the screen using library macros and procedures.

The Library and INCLUDE

A Library of Common Functions

  • Frequently used routines come ready-made, so you don't have to write them yourself.
  • Routines defined in other files are brought in with the INCLUDE directive.
  • To use anything in emu8086.inc, put include 'emu8086.inc' at the top of the source file.
  • The library covers the screen, keyboard and number routines most emu8086 programs need.
include'emu8086.inc'1. the source file'sfolderif not found2. the emu8086 install'sInc folderthe file's text replaces the include line

INCLUDE is a directive: it generates no machine code, it just inserts text at assembly time.

The Library and INCLUDE

The Source After INCLUDE

; in place of the include line:
PUTC MACRO char     ; template: 0 bytes
  ...
ENDM
GOTOXY MACRO col, row
  ...
ENDM
DEFINE_SCAN_NUM MACRO
  ...               ; procedure template
ENDM
; the program itself:
ORG  100h
PUTC 'A'            ; 8 bytes here
RET
  • The assembler replaces the include line with the file's text, then assembles the result as one source.
  • A macro definition is only a template: an unused macro adds no bytes at all.
  • Code appears where the macro is used: PUTC 'A' expands into 8 bytes of instructions.
  • Procedures are wrapped in macros too (DEFINE_…): without its DEFINE_ line, a procedure never enters the program.
  • Including the whole library costs nothing: program size depends only on the macros you use and the procedures you define.
At run time there is no “emu8086.inc”: memory holds only expanded instructions and the procedures you defined.

The Library and INCLUDE

What's in the Library?

Macros · used directly
MacroPurpose
PUTC charprint one character
GOTOXY col, rowposition the cursor
PRINT stringprint a string
PRINTN stringprint a string + newline
CURSOROFFhide the cursor
CURSORONshow the cursor
Procedures · DEFINE_ + CALL
ProcedurePurpose
PRINT_STRINGprint the string at DS:SI
PTHISprint the string after the CALL
GET_STRINGread a string from the keyboard
CLEAR_SCREENclear the screen
SCAN_NUMread a number → CX
PRINT_NUMprint AX as signed
PRINT_NUM_UNSprint AX as unsigned
Macros are copied to every place they are used; procedures are defined once and called with CALL.

Macros

Screen Macros

MacroWhat it doesUnder the hood
PUTC charPrints one ASCII character at the cursor.INT 10h, AH = 0Eh
GOTOXY col, rowMoves the cursor to the given column and row.INT 10h, AH = 02h
PRINT stringPrints the given string.0Eh, one character at a time
PRINTN stringLike PRINT, then adds CR + LF (13, 10) to start a new line.0Eh, one character at a time
CURSOROFFTurns the text cursor off (hides it).INT 10h, AH = 01h
CURSORONTurns the text cursor back on.INT 10h, AH = 01h
Macro arguments can be constants, registers or variables: PUTC 65, PUTC 'B', PUTC AL.

Macros

What Do PUTC and GOTOXY Expand To?

PUTC 'A'

PUSH AX        ; save AX
MOV  AL, 'A'   ; argument
MOV  AH, 0Eh   ; teletype
INT  10h
POP  AX        ; restore AX

5 instructions, 8 bytes. Registers are preserved; the calling code is unaffected.

GOTOXY 10, 5

PUSH AX
PUSH BX
PUSH DX
MOV  AH, 02h   ; set cursor
MOV  DH, 5     ; row
MOV  DL, 10    ; column
MOV  BH, 0     ; page 0
INT  10h
POP  DX
POP  BX
POP  AX
The argument order is column, row (x, y); the BIOS takes the column in DL and the row in DH. Top left is (0, 0), bottom right (79, 24).

Macros · Step through the code

Code Trace: PRINT, GOTOXY, PUTC

0510150123456… 80 × 25

include: macro definitions are inserted at assembly time; no code is generated.

0510150123456… 80 × 25

ORG 100h: a COM program starts at 100h.

0510150123456Hello World!… 80 × 25

PRINT: 12 characters printed (columns 0–11); the cursor is at column 12.

0510150123456Hello World!… 80 × 25

GOTOXY 10, 5: the cursor moves to column 10, row 5. Nothing is printed.

0510150123456Hello World!A… 80 × 25

PUTC 65: 65 = 41h = 'A' is printed; the cursor moves to column 11.

0510150123456Hello World!AB… 80 × 25

PUTC 'B': a character literal works too.

0510150123456Hello World!AB… 80 × 25

RET: return to DOS. END just tells the assembler the source ends here.

include emu8086.inc
ORG    100h
PRINT 'Hello World!'
GOTOXY 10, 5
PUTC 65           ; 65 - is an ASCII code for 'A'
PUTC 'B'
RET               ; return to operating system.
END               ; directive to stop the compiler.

Macros

PRINTN and the Cursor Macros

PRINT vs. PRINTN

PRINT 'a' then PRINT 'b' → ab on one line.

PRINTN 'a' then PRINT 'b' → a and, on the next line, b.

CR (13) moves the cursor to the start of the line, LF (10) moves it down a line; a newline needs both.

abCR (13): line startLF (10): next line
CURSOROFF / CURSORON

They use INT 10h, AH = 01h (cursor shape): CH = start, CL = end scan line.

Setting bit 5 of CH hides the cursor; CURSORON restores the normal shape.

Handy for hiding the blinking cursor on game or menu screens.

PRINTN 'Full name:'  ; print, then newline
CURSOROFF
GOTOXY 30, 12
PRINT 'Hello'
CURSORON

Macros

Control Characters with PUTC

CodeNamePUTC effect
07hBELA short beep from the speaker; the cursor doesn't move.
08hBS (backspace)Cursor steps left; it does not erase the character. No effect in column 0.
0AhLF (line feed)Cursor moves down a row; the column stays. On the last row the screen scrolls up one line.
0DhCR (carriage return)Cursor returns to column 0 of the same row; the text stays put.
Newline = CR + LF

The 13, 10 pair that PRINTN appends combines both moves: line start, then down a line. In reverse order (10, 13) the cursor ends up in the same place.

Erasing on screen

To erase a character, use the triple PUTC 8, PUTC ' ', PUTC 8: step left, overwrite with a space, step left again. The library procedures that handle backspace fix the screen the same way.

Macros · Step through the code

Code Trace: CR and LF Separately

AL61hcursor (col, row)(1, 0)screena

AH = 0Eh is loaded only once here; INT 10h prints the 'a' in AL and moves the cursor right to (1, 0).

AL62hcursor (col, row)(2, 0)screenab

'b' is printed; cursor at (2, 0).

AL0Ahcursor (col, row)(2, 1)screenab

LF alone (10): the cursor drops one row but stays in column 2: (2, 1).

AL63hcursor (col, row)(3, 1)screenabc

'c' lands in column 2 of the next row: the text “staircases”.

AL0Dhcursor (col, row)(0, 1)screenabc

CR alone (13): the cursor returns to the start of the same row, (0, 1). The c is not erased.

AL64hcursor (col, row)(1, 1)screenabdc

'd' goes into column 0. The screen shows “ab” with “d c” below. A proper newline needs both 13 and 10.

ORG  100h
MOV  AH, 0Eh     ; teletype
MOV  AL, 'a'
INT  10h
MOV  AL, 'b'
INT  10h
MOV  AL, 10      ; LF only
INT  10h
MOV  AL, 'c'
INT  10h
MOV  AL, 13      ; CR only
INT  10h
MOV  AL, 'd'
INT  10h
RET

Macros

Line Wrap and Scrolling

  • After writing column 79, service 0Eh moves the cursor to the start of the next row by itself, so PRINT continues a long string without a break.
  • If the cursor has to move down from the last row (24), the whole screen scrolls up one row: the top row disappears and a blank row appears at the bottom.
  • Example: GOTOXY 75, 24 then PRINT 'Welcome'. “Welco” fills columns 75–79; for “me” the screen scrolls. In the end “Welco” is on row 23, “me” at the start of row 24, and the cursor at (2, 24).
  • GOTOXY and PUTC do no bounds checking: keep positions within 0–79 (column) and 0–24 (row).
column01234…7576777879row 23…Welcorow 24me…cursor

Macros

Demo: The GOTOXY Screen

Click a cell on the 80 × 25 text screen to see the macro that moves the cursor there, the BIOS registers it sets and the matching video memory address.

Macros · Step through the code

Code Trace: Two Digits with AAM and PUTC

AH00hAL3AhSPFFFEhstackFFFC····FFFE0000hSPscreen▌

AL = 58 (3Ah). Goal: print it as two decimal digits.

AH05hAL08hSPFFFEhstackFFFC····FFFE0000hSPscreen▌

AAM divides AL by 10: AH = 5 (tens), AL = 8 (ones). Only AL is divided, so the number must be 0–99.

AH35hAL38hSPFFFEhstackFFFC····FFFE0000hSPscreen▌

ADD AX, 3030h adds 30h to both bytes at once: AH = '5' (35h), AL = '8' (38h).

AH35hAL38hSPFFFChstackFFFC3538hSPFFFE0000hscreen▌

PUTC AH expansion: first AX (3538h) is pushed, SP = FFFCh.

AH0EhAL35hSPFFFChstackFFFC3538hSPFFFE0000hscreen5▌

MOV AL, AH and MOV AH, 0Eh: AX = 0E35h; the ones digit is gone from the register. INT 10h prints 5.

AH35hAL38hSPFFFEhstackFFFC····FFFE0000hSPscreen5▌

POP AX: AX = 3538h is back; '8' is in AL again.

AH35hAL38hSPFFFEhstackFFFC····FFFE0000hSPscreen58▌

PUTC AL expands the same way (MOV AL, AL is harmless). The screen shows 58; AX is still 3538h. Because PUTC preserves AX, both digits print without copying them to another register.

ORG  100h
MOV  AL, 58
AAM              ; AH = 5, AL = 8
ADD  AX, 3030h   ; '5', '8'
PUSH AX          ; PUTC AH expanded
MOV  AL, AH
MOV  AH, 0Eh
INT  10h
POP  AX          ; AX back: 3538h
PUSH AX          ; PUTC AL expanded
MOV  AL, AL
MOV  AH, 0Eh
INT  10h
POP  AX
RET

Procedures

Using Procedures: DEFINE_ and CALL

include 'emu8086.inc'
ORG 100h
    ...
    CALL print_num   ; use
    ...
RET

DEFINE_PRINT_NUM    ; define
DEFINE_PRINT_NUM_UNS
END
  • Each procedure must be defined once, before the END directive, with its own DEFINE_… macro.
  • A DEFINE_… macro expands the procedure's code right where it appears.
  • Definitions usually go between RET and END. Every DEFINE_ macro starts with a JMP over the body, so execution never falls into the procedure.
  • In the code you CALL a procedure by name, written in lower case (print_num).
  • PRINT_NUM calls PRINT_NUM_UNS internally, so both must be defined.
main code … CALL print_num …RETprint_numprint_num_unsENDCALLtop-down flowwhere the DEFINE_… macros expand

Procedures

Input and Output Registers

ProcedureInputOutputNotes
PRINT_STRINGDS:SI = string address—string must end in 0
PTHISstring right after the CALL—advances the return address itself
GET_STRINGDS:DI = buffer, DX = size0-terminated string in the bufferat most DX − 1 characters
CLEAR_SCREEN——cursor goes to (0, 0)
SCAN_NUMkeyboardCX (signed)old value of CX is lost
PRINT_NUMAX (signed)—PRINT_NUM_UNS must be defined too
PRINT_NUM_UNSAX (unsigned)—0 … 65,535
Library procedures push every other register they use on entry and restore it on exit; only the output register changes. A program that keeps a loop counter in CX must save it before calling SCAN_NUM (PUSH CX … POP CX).

Procedures

String Procedures

PRINT_STRING
  • Prints a null-terminated (0) string at the cursor.
  • Takes the string address from DS:SI.
  • Defined by: DEFINE_PRINT_STRING.
LEA  SI, msg
CALL print_string
msg DB 'Hello', 0
PTHIS
  • Prints a null-terminated string.
  • Takes the address from the stack: the string is placed right after the CALL.
  • Defined by: DEFINE_PTHIS.
CALL pthis
DB 'Hello', 0
; execution resumes here
The PRINT macro copies its code at every use; PRINT_STRING and PTHIS print any number of strings with a single copy of the code.

Procedures

Ways to Print a String

MethodWhere is the string?TerminatorHow is the address passed?Best for
PRINT 'text'inside the code (macro expansion)0 (added by the macro)handled by the macro (CS:SI)a constant message printed once
PRINT_STRINGin the data area0DS:SIstrings printed in several places or built at run time
PTHISright after the CALL0return address on the stackmany short constant messages
INT 21h, AH = 09hin the data area'$'DS:DXDOS programs without the library
The terminator can't be printed

A '$'-terminated string cannot contain '$', and a 0-terminated one cannot contain a 0 byte: the string ends there.

Match the buffer to the method

The buffer GET_STRING fills ends in 0, so print it with PRINT_STRING. With AH = 09h, memory is dumped to the screen until a '$' turns up.

Procedures

GET_STRING and CLEAR_SCREEN

GET_STRING
  • Reads a null-terminated string from the user.
  • The string is stored in the buffer at DS:DI.
  • DX = buffer size; a 0 is appended, so at most DX − 1 characters are read.
  • Enter ends the input.
  • Defined by: DEFINE_GET_STRING.
CLEAR_SCREEN
  • Clears the screen and moves the cursor to the top-left corner (0, 0).
  • Defined by: DEFINE_CLEAR_SCREEN.
LEA  DI, buf         ; buffer
MOV  DX, 20          ; size
CALL get_string
CALL clear_screen
LEA  SI, buf
CALL print_string
RET
buf DB 20 DUP(0)

Procedures · Step through the code

Code Trace: GET_STRING Logic (DX = 4)

AL00hDI011DhDX0004hZF0CF0buffer?buf+0?buf+1?buf+2?buf+3DIDX = 4screen▌

A simplified GET_STRING read loop (the library version also handles backspace). DI = buffer, DX = 4 bytes; the user will type “Ece”.

AL00hDI011DhDX0004hZF0CF0buffer?buf+0?buf+1?buf+2?buf+3DIDX = 4screen▌

4 > 1: room for a character plus the final 0 → JBE is not taken.

AL45hDI011DhDX0004hZF0CF0buffer?buf+0?buf+1?buf+2?buf+3DIDX = 4screenE▌

INT 21h, AH = 01h: 'E' is read and echoed. Not Enter (13) → JE is not taken.

AL45hDI011EhDX0003hZF0CF0buffer'E'buf+0?buf+1?buf+2?buf+3DIDX = 3screenE▌

'E' goes into the buffer; DI advances, room left DX = 3.

AL63hDI011FhDX0002hZF0CF0buffer'E'buf+0'c'buf+1?buf+2?buf+3DIDX = 2screenEc▌

Second pass: 'c' is read and stored at buf+1; DX = 2.

AL65hDI0120hDX0001hZF0CF0buffer'E'buf+0'c'buf+1'e'buf+2?buf+3DIDX = 1screenEce▌

Third pass: 'e' goes to buf+2; DX = 1.

AL65hDI0120hDX0001hZF1CF0buffer'E'buf+0'c'buf+1'e'buf+2?buf+3DIDX = 1screenEce▌

DX = 1: room only for the final 0 → JBE done. Further keys are not read: at most DX − 1 = 3 characters.

AL65hDI0120hDX0001hZF1CF0buffer'E'buf+0'c'buf+1'e'buf+20buf+3DIDX = 1screenEce▌

The string gets its 0 terminator: buffer 'E','c','e',0 → ready for PRINT_STRING.

LEA  DI, buf      ; buffer address
MOV  DX, 4       ; buffer size
get_key: CMP DX, 1   ; keep 1 byte for the 0
JBE  done
MOV  AH, 01h
INT  21h         ; AL = key (echoed)
CMP  AL, 13      ; Enter?
JE   done
MOV  [DI], AL    ; store in buffer
INC  DI
DEC  DX
JMP  get_key
done: MOV BYTE PTR [DI], 0
RET
buf   DB 4 DUP(?)

Procedures

GET_STRING Details

Controlled echo

The library version reads keys without echo (INT 16h, AH = 0) and echoes only the characters it stores, so rejected keys leave no trace on screen.

Full buffer

After DX − 1 characters, further letters are ignored; the procedure waits for Enter or backspace. Unlike the simplified trace, it does not stop by itself.

Backspace (8)

If the buffer holds a character, DI steps back and 8, ' ', 8 is printed. On an empty buffer the key is ignored: the cursor never moves left of the input start.

Enter (13)

It is not stored; a 0 goes in its place and the procedure returns. With DX ≤ 1 nothing is read at all, since there is room only for the final 0.

After GET_STRING the cursor stays just right of the input, so the next output starts on the same line. Add PUTC 13 and PUTC 10 to move down.

Procedures · Step through the code

Code Trace: Reading with Backspace

AL00hDIbuf+0buf?+0?+1?+2?+3?+4?+5DIscreen

Buffer buf is 6 bytes; DI points to its first byte. The user will press A, b, backspace, c and Enter.

AL41hDIbuf+0buf?+0?+1?+2?+3?+4?+5DIscreen

INT 16h: AL = 'A' (41h); the key is read without echo, so the screen is still empty. Neither Enter (13) nor backspace (8): store.

AL41hDIbuf+1buf'A'+0?+1?+2?+3?+4?+5DIscreenA

'A' is stored and DI advances; then the echo: A on screen.

AL62hDIbuf+2buf'A'+0'b'+1?+2?+3?+4?+5DIscreenAb

Same path for 'b': buffer A, b; DI = buf+2; the screen shows Ab.

AL08hDIbuf+2buf'A'+0'b'+1?+2?+3?+4?+5DIscreenAb

Backspace: AL = 08h. CMP AL, 8 → ZF = 1, JNE store is not taken.

AL08hDIbuf+1buf'A'+0'b'+1?+2?+3?+4?+5DIscreenAb

DI is not at the buffer start (buf+2 ≠ buf): there is a character to erase. DEC DI frees b's byte; it stays in memory but is no longer part of the string.

AL08hDIbuf+1buf'A'+0'b'+1?+2?+3?+4?+5DIscreenA

On screen, the triple: 8 moves the cursor left, a space overwrites b, the second 8 moves left again. Only A remains.

AL63hDIbuf+2buf'A'+0'c'+1?+2?+3?+4?+5DIscreenAc

'c' goes into b's old byte: buffer A, c; the screen shows Ac.

AL0DhDIbuf+2buf'A'+0'c'+10+2?+3?+4?+5DIscreenAc

Enter: JE done; a 0 is written where DI points. Buffer 'A', 'c', 0: the erased letter is gone.

ORG  100h
LEA  DI, buf
get_key: MOV AH, 0
INT  16h         ; AL = key (no echo)
CMP  AL, 13      ; Enter?
JE   done
MOV  AH, 0Eh
CMP  AL, 8       ; backspace?
JNE  store
CMP  DI, OFFSET buf
JE   get_key         ; nothing to erase
DEC  DI
INT  10h         ; 8: cursor left
MOV  AL, ' '
INT  10h         ; blank the char
MOV  AL, 8
INT  10h         ; left again
JMP  get_key
store: MOV [DI], AL
INC  DI
INT  10h         ; echo
JMP  get_key
done: MOV BYTE PTR [DI], 0
RET
buf   DB 6 DUP(?)

Procedures

Number Procedures

ProcedureWhat it doesInput / outputDefined by
SCAN_NUMReads a multi-digit signed number from the keyboard (ends with Enter).output: CXDEFINE_SCAN_NUM
PRINT_NUMPrints the signed number in AX in decimal.input: AXDEFINE_PRINT_NUM + DEFINE_PRINT_NUM_UNS
PRINT_NUM_UNSPrints the unsigned number in AX.input: AXDEFINE_PRINT_NUM_UNS
Signed range

16 bits: −32,768 … 32,767

Unsigned range

16 bits: 0 … 65,535

Same bits

FFE7h = −25 (signed) = 65,511 (unsigned)

Procedures · Step through the code

Code Trace: SCAN_NUM Logic (input 307)

AX0000hCX0000hBX0000hZF1CX decimal:0screen▌

The core of SCAN_NUM: digits are read left to right, result = result × 10 + digit (the library version also handles a minus sign and overflow). CX = 0.

AX0133hCX0000hBX0000hZF1CX decimal:0screen3▌

INT 21h, AH = 01h: key '3', AL = 33h; the character is echoed.

AX0103hCX0000hBX0000hZF0CX decimal:0screen3▌

Not Enter. SUB AL, '0': 33h − 30h = 3.

AX0000hCX0003hBX0000hZF0CX decimal:3screen3▌

CBW sets AX = 0003h; XCHG swaps: AX = old result (0), CX = digit (3).

AX0000hCX0003hBX000AhZF0CX decimal:3screen3▌

MUL BX: 0 × 10 = 0; ADD CX, AX → CX = 3.

AX0003hCX0000hBX000AhZF1CX decimal:0screen30▌

'0' is read: digit 0; after XCHG, AX = 3, CX = 0.

AX001EhCX001EhBX000AhZF0CX decimal:30screen30▌

3 × 10 = 30 (1Eh) → CX = 30 + 0 = 30.

AX0007hCX001EhBX000AhZF0CX decimal:30screen307▌

'7' is read: digit 7 into AX (CBW); the result 30 is still in CX.

AX012ChCX0133hBX000AhZF0CX decimal:307screen307▌

XCHG: AX = 30, CX = 7. 30 × 10 = 300 (012Ch) → CX = 300 + 7 = 307 = 0133h.

AX010DhCX0133hBX000AhZF1CX decimal:307screen307▌

Enter: AL = 0Dh = 13 → ZF = 1, JE done is taken.

AX010DhCX0133hBX000AhZF1CX decimal:307screen307▌

As in SCAN_NUM, the result is in CX: 0133h = 307.

ORG  100h
XOR  CX, CX      ; result = 0
get_key: MOV AH, 01h
INT  21h         ; AL = key (echoed)
CMP  AL, 13      ; Enter?
JE   done
SUB  AL, '0'     ; ASCII → digit
CBW              ; AX = digit
XCHG AX, CX      ; AX=result, CX=digit
MOV  BX, 10
MUL  BX          ; AX = result × 10
ADD  CX, AX      ; CX = result×10 + digit
JMP  get_key
done: RET

Procedures

What SCAN_NUM Checks

  • The - key sets a sign flag; on Enter, if the flag is set, NEG CX is applied.
  • A non-digit key is erased from the screen (8, ' ', 8) and ignored.
  • Backspace drops the last digit: CX ← CX / 10.
  • If the number would not fit in 16 bits (the × 10 or the addition overflows), the last digit is rejected.
  • Enter is echoed too: the cursor returns to the line start (CR) but does not move down. That is why the PTHIS string in the example program starts with 13, 10.
InputCXPRINT_NUM
3070133h307
-25FFE7h-25
12a3007Bh123
400009C40h-25536
700001B58h7000
-4000063C0h25536
Digits accumulate as an unsigned 16-bit value and the sign is applied last, so inputs outside −32,768 … 32,767 silently give a wrongly signed result. (The table comes from running code equivalent to the library routine.)

Procedures · Step through the code

Code Trace: PRINT_NUM_UNS Logic (AX = 1205)

AX04B5hDX0000hCX0000hAX decimal:1205stackFFF6····FFF8····FFFA····FFFC····screen▌

Equivalent code with the same output (the library version divides by 10000, 1000, …). AX = 1205 = 04B5h, divisor BX = 10.

AX0078hDX0005hCX0001hAX decimal:120stackFFF6····FFF8····FFFA····FFFC0005hSPscreen▌

DIV BX: DX:AX / 10 → AX = 120, remainder DX = 5. The last digit is pushed, CX = 1.

AX000ChDX0000hCX0002hAX decimal:12stackFFF6····FFF8····FFFA0000hSPFFFC0005hscreen▌

AX ≠ 0 → loop again: 120 / 10 = 12, remainder 0 pushed; CX = 2.

AX0001hDX0002hCX0003hAX decimal:1stackFFF6····FFF80002hSPFFFA0000hFFFC0005hscreen▌

12 / 10 = 1, remainder 2 pushed; CX = 3.

AX0000hDX0001hCX0004hAX decimal:0stackFFF60001hSPFFF80002hFFFA0000hFFFC0005hscreen▌

1 / 10 = 0, remainder 1 pushed; CX = 4 digits.

AX0000hDX0001hCX0004hAX decimal:0stackFFF60001hSPFFF80002hFFFA0000hFFFC0005hscreen▌

OR AX, AX: AX = 0 → ZF = 1, JNZ is not taken. The most significant digit (1) is on top of the stack.

AX0E31hDX0001hCX0003hstackFFF6····FFF80002hSPFFFA0000hFFFC0005hscreen1▌

POP AX = 1; + '0' = 31h; INT 10h prints '1'. LOOP: CX = 3.

AX0E32hDX0001hCX0002hstackFFF6····FFF8····FFFA0000hSPFFFC0005hscreen12▌

Next digit 2 → '2'. CX = 2.

AX0E30hDX0001hCX0001hstackFFF6····FFF8····FFFA····FFFC0005hSPscreen120▌

0 → '0'. CX = 1.

AX0E35hDX0001hCX0000hstackFFF6····FFF8····FFFA····FFFC····screen1205▌

5 → '5'. CX = 0, the loop ends; SP is back at FFFEh. The screen shows 1205.

ORG  100h
MOV  AX, 1205    ; number to print
MOV  BX, 10
XOR  CX, CX      ; digit counter
divide: XOR DX, DX
DIV  BX          ; AX=quot, DX=rem
PUSH DX          ; push the digit
INC  CX
OR   AX, AX      ; quotient 0?
JNZ  divide
emit: POP AX      ; MSD first
ADD  AL, '0'
MOV  AH, 0Eh
INT  10h
LOOP emit
RET

Procedures

The Library's Method: A Shrinking Divisor

  • The divisor starts at 10,000 and is divided by 10 each pass; printing stops when it reaches 0.
  • The quotient (0–9) is one digit, printed after ADD AL, 30h; the remainder becomes the number for the next pass.
  • A flag (CX = 1) skips leading zeros; once the first digit is printed the flag is cleared and inner zeros are printed.
  • A separate branch prints '0' directly when AX = 0.
  • Since 65,535 ÷ 10,000 = 6, the quotient always fits in AL.
DivisorNumberStepScreen
100003007number < divisor, no digit yet: skip—
100030073007 ÷ 1000 = 3, rem. 73
10077 ÷ 100 = 0, rem. 730
1077 ÷ 10 = 0, rem. 7300
177 ÷ 1 = 7, rem. 03007
Digits are printed left to right as they are computed; no pushing and no reversing needed.

Procedures · Step through the code

Code Trace: PRINT_NUM and the Minus Sign

AXFFE7hSPFFFEhSF0stackFFF8····FFFA····FFFC····FFFE0000hSPscreen▌

AX = −25, which is FFE7h in two's complement. The code shown is equivalent to the library's PRINT_NUM.

AXFFE7hSPFFFChSF0stackFFF8····FFFA····FFFC0106hSPFFFE0000hscreen▌

CALL print_num: return address 0106h is pushed, SP = FFFCh.

AXFFE7hSPFFFAhSF1stackFFF8····FFFAFFE7hSPFFFC0106hFFFE0000hscreen▌

PUSH AX saves the caller's value. OR AX, AX leaves the value unchanged but sets the flags: MSB is 1 → SF = 1.

AX0019hSPFFFAhSF0stackFFF8····FFFAFFE7hSPFFFC0106hFFFE0000hscreen▌

JNS is not taken (the number is negative). NEG AX: 0 − FFE7h = 0019h = 25, the absolute value.

AX0019hSPFFFAhSF0stackFFF8····FFFAFFE7hSPFFFC0106hFFFE0000hscreen-▌

PUTC '-' expansion: AX is pushed, '-' is printed, AX = 0019h is restored.

AX0019hSPFFFAhSF0stackFFF8····FFFAFFE7hSPFFFC0106hFFFE0000hscreen-25▌

CALL print_num_uns: the digits of 25 are printed (same digit loop as in the PRINT_NUM_UNS trace; the procedure saves the registers it uses).

AXFFE7hSPFFFChSF0stackFFF8····FFFA····FFFC0106hSPFFFE0000hscreen-25▌

POP AX: AX is FFE7h again. The number is still in AX after printing.

AXFFE7hSPFFFEhSF0stackFFF8····FFFA····FFFC····FFFE0000hSPscreen-25▌

Both RETs: SP = FFFEh. The library's PRINT_NUM also prints '0' directly when AX = 0.

ORG  100h
MOV  AX, -25       ; AX = FFE7h
CALL print_num
RET
print_num PROC
PUSH AX
OR   AX, AX        ; SF = sign bit
JNS  positive
NEG  AX            ; AX = 0019h
PUSH AX            ; PUTC '-' expanded
MOV  AL, '-'
MOV  AH, 0Eh
INT  10h
POP  AX
positive: CALL print_num_uns
POP  AX            ; AX = FFE7h again
RET
print_num ENDP

Procedures

Extracting Digits: Two Methods

CriterionStack method (divide by 10, push, pop in reverse)Shrinking divisor (10,000, 1000, …)
Divisionsone per digitup to five, plus one each to shrink the divisor
Stack use2 bytes per digitonly the saved registers
Leading zerosnever appearskipped with a flag
Fixed width (00042)needs extra codefree: just drop the flag
Other basesuse divisor 2, 8 or 16; in base 16, digits above 9 become 'A'–'F'the divisor sequence depends on the base (4096, 256, 16, 1 for base 16)
Output orderdigits go to the stack, then to the screen in reverseleft to right, as computed
Both methods give the same output: for 1205 each prints the digits 1, 2, 0, 5. Stack use, fixed width and the base you need decide which to pick.

Procedures

Demo: PRINT_NUM and PRINT_NUM_UNS

Enter a value for AX (decimal, negative, or hex with an h suffix) to see what each procedure prints.

Example Program · Step through the code

Code Trace: Read and Print a Number

LEA SI, msg1: SI ← offset of the msg1 string.

CALL print_string: the return address is pushed (SP = FFFCh); the procedure prints the string at DS:SI up to the 0.

CALL scan_num: the user types -25 and presses Enter; the keys are echoed.

On return: CX = FFE7h = −25 (two's complement). SP is back at FFFEh.

MOV AX, CX: PRINT_NUM expects the number in AX.

CALL pthis: the “return address” it pushes is really the address of the string on the next line.

PTHIS prints the string: 13, 10 (newline) and “You have entered: ”. Then it moves the return address past the 0.

Execution returns past the string. CALL print_num: AX = FFE7h is printed as signed.

RET: 0000h is popped into IP, SP = 0000h; back to DOS. Lines 11–17 are data and procedure definitions, never executed in this flow.

include 'emu8086.inc'
ORG    100h
LEA    SI, msg1       ; ask for the number
CALL   print_string   ;
CALL   scan_num       ; get number in CX.
MOV    AX, CX         ; copy the number to AX.
CALL   pthis          ; print the following string:
DB  13, 10, 'You have entered: ', 0
CALL   print_num      ; print number in AX.
RET                   ; return to operating system.
msg1   DB  'Enter the number: ', 0
DEFINE_SCAN_NUM
DEFINE_PRINT_STRING
DEFINE_PRINT_NUM
DEFINE_PRINT_NUM_UNS  ; required for print_num.
DEFINE_PTHIS
END                   ; directive to stop the compiler.

Example Program

How PTHIS Works

CALL pthis0D0A'You have entered: '00CALL print_numcode segment (memory, addresses increase to the right)stack:—← SP = FFFEh

In memory, the string bytes follow CALL pthis directly; the string ends in 0.

CALL pthis0D0A'You have entered: '00CALL print_numcode segment (memory, addresses increase to the right)stack:addr(0Dh)← SP = FFFCh

CALL pushes the address of the “next instruction”, which is really the address of 0Dh, the first byte of the string.

CALL pthis0D0A'You have entered: '00CALL print_numcode segment (memory, addresses increase to the right)stack:addr(0Dh)← SP = FFFCh

PTHIS reads that address from the stack and prints bytes from there up to the 0.

CALL pthis0D0A'You have entered: '00CALL print_numcode segment (memory, addresses increase to the right)stack:addr(CALL print_num)← SP = FFFCh

The address on the stack is replaced by the one just past the 0 byte: it now points to CALL print_num.

CALL pthis0D0A'You have entered: '00CALL print_numcode segment (memory, addresses increase to the right)stack:—← SP = FFFEh

RET: the CPU skips the string and continues at CALL print_num. The data is never executed as code.

The trick relies on the return address being kept on the stack. The PRINT macro also embeds data in the code, but jumps over it with JMP.

Example Program

Example: Adding Two Numbers

include 'emu8086.inc'
ORG  100h
CALL scan_num     ; 1st number → CX
MOV  BX, CX       ; save it
PUTC 13
PUTC 10           ; next line
CALL scan_num     ; 2nd number → CX
PUTC 13
PUTC 10
MOV  AX, BX
ADD  AX, CX       ; signed sum
JO   overflow
CALL print_num
RET
overflow: PUTC '?'
RET
DEFINE_SCAN_NUM
DEFINE_PRINT_NUM
DEFINE_PRINT_NUM_UNS
END
  • The second SCAN_NUM also returns in CX, so the first number is saved in BX.
  • Enter only returns to the line start; PUTC 13, PUTC 10 move the next input down a line.
  • JO catches signed overflow: 30,000 + 5000 = 35,000 exceeds the 16-bit signed range (32,767).
InputsScreen (last line)
120, -4575
-7, -8-15
30000, 5000?

Example Program

Example: A Framed Title

include 'emu8086.inc'
ORG  100h
CALL clear_screen
GOTOXY 10, 2
CALL hline
GOTOXY 10, 3
PRINT '|  HEADER  |'
GOTOXY 10, 4
CALL hline
GOTOXY 0, 6       ; cursor below
RET
hline PROC        ; +----------+
PUTC '+'
MOV  CX, 10
dash: PUTC '-'
LOOP dash
PUTC '+'
RET
hline ENDP
DEFINE_CLEAR_SCREEN
END
0123456+----------+|HEADER|+----------+columns 10 … 21
  • Our own procedure (hline) works alongside the library macros; it is defined after RET.
  • The PUTC '-' inside the loop is expanded once and runs 10 times: the code is not copied 10 times.
  • PUTC uses only AX and restores it; it never touches CX, so the loop counter is safe.

Example Program

Common Mistakes

Forgetting DEFINE_

CALL scan_num without DEFINE_SCAN_NUM: the assembler reports an undefined label.

Where DEFINE_ goes

Every DEFINE_ macro starts with JMP skip_proc_…, so even at the top of the program the CPU skips the body. The usual place is still between RET and END.

Missing the 0 terminator

PRINT_STRING and PTHIS print until they see a 0; without one, random memory bytes spill onto the screen.

Assuming registers survive

Procedures return results in specific registers (SCAN_NUM → CX). Don't assume any other register is preserved unless the documentation says so.

At the top: a wasted JMPORG 100hDEFINE_SCAN_NUMmain programRETUsual placeORG 100hmain programRETDEFINE_SCAN_NUMEND← skipped by JMP← reached only by CALL

Example Program

Number and Screen Mistakes

Looking for the result in AX

SCAN_NUM returns in CX. Forget MOV AX, CX before PRINT_NUM and the stale AX is printed.

Printing unsigned as signed

AX = 40,000 (9C40h) shows up as −25536 with PRINT_NUM. Unsigned values that can exceed 32,767 need PRINT_NUM_UNS.

Expecting a new line after Enter

After SCAN_NUM the cursor is at the start of the input line, so the next output overwrites the number. Put CR + LF in between.

Mixing up row and column

GOTOXY 5, 10 moves the cursor to column 5, row 10, not the other way round.

Passing a register the expansion clobbers

GOTOXY AL, AH: the macro loads 02h into AH first, so the row becomes 02h. Move the position into other registers first.

Overstating the buffer size

If DX exceeds the real buffer size, GET_STRING overwrites the variables that follow the buffer.

Lab · library macros and procedures

Lab: The emu8086.inc Library

Summary

Summary

INCLUDE

include 'emu8086.inc': searched in the source folder first, then in the Inc folder.

Macros

PUTC, GOTOXY (col, row), PRINT, PRINTN, CURSOROFF, CURSORON: built on INT 10h, expanded wherever they are used.

Procedures

Define with DEFINE_… before END, call with CALL. Input/output registers: SI, DI, DX, CX, AX.

Numbers

SCAN_NUM → CX (signed); PRINT_NUM prints AX as signed, PRINT_NUM_UNS as unsigned.

PTHIS

The string sits right after the CALL; the procedure moves the return address past it.

Strings

PRINT embeds the string in the code; PRINT_STRING and PTHIS print 0-terminated strings with one copy of the code; GET_STRING ends its buffer with 0.

Summary

Exercises

  1. With macros, print “CENTER” mid-screen (column 35, row 12).
  2. Read two numbers from the user and print their sum.
  3. If PRINT is used 10 times, how many copies of the strings and loop code does the program hold? Compare with PRINT_STRING.
  4. What do PRINT_NUM and PRINT_NUM_UNS print when AX = 8000h?
  5. What happens if DEFINE_PTHIS is placed right below ORG 100h?
  6. Read the user's name with GET_STRING and print “Hello, name!”.
Hints / answers
  1. GOTOXY 35, 12, then PRINT 'CENTER', RET.
  2. CALL scan_num → MOV BX,CX → PUTC 13/10 → CALL scan_num → MOV AX,BX, ADD AX,CX, CALL print_num; DEFINE_SCAN_NUM, DEFINE_PRINT_NUM, DEFINE_PRINT_NUM_UNS.
  3. PRINT: 10 copies (each with its own string and loop). PRINT_STRING: one loop, 10 strings + 10 × (LEA + CALL).
  4. PRINT_NUM: −32768, PRINT_NUM_UNS: 32768.
  5. It still works: the macro's JMP skip_proc_pthis skips the body; the only cost is one extra JMP.
  6. LEA DI,buf / MOV DX,20 / CALL get_string, PUTC 13/10, PRINT 'Hello, ', LEA SI,buf / CALL print_string, PUTC '!'.

Summary

References

  • emu8086 help: the “emu8086.inc — library of common functions” and “Macros” pages.
  • The Inc/emu8086.inc file in the emu8086 installation (source code of the macros and procedures).
  • B. B. Brey, The Intel Microprocessors, 8th ed., Pearson, 2009 — procedures and macros.
  • A. S. Tanenbaum, Modern Operating Systems, 3rd ed., Pearson, 2008.

The End

Chapter 9.2: The emu8086.inc Library
Previous: Chapter 9.1: Macros · Next: Chapter 10.1: 8086 Pins
1 / 1 Sercan KÜLCÜ. All rights reserved.