Microprocessors · Lecture Notes

Chapter 5.2: Interrupt Functions

An 8086 program does not have to drive the hardware from scratch every time it wants to print text on the screen, read a key from the keyboard, or find out the time. The BIOS in the computer's ROM, and DOS running on top of it, offer these jobs as ready-made routines. A program reaches these routines through a software interrupt: it writes the service number into register AH and the parameters into the other registers, then executes an INT n instruction. These notes cover the services of the four most used interrupts: INT 10h manages the screen, INT 16h the keyboard, INT 21h the DOS character, string, date and time services, and INT 1Ah the clock counter. Writing directly to screen memory without the BIOS, the BIOS data area, and the proper ways to terminate a program are also covered. Each service is shown at register level by the step-by-step trace of a short program.

Learning outcomes

Call services
Call BIOS and DOS services with the service number in AH and register parameters; know in advance which registers will change.
Write to the screen
Print characters, colored characters and strings with INT 10h and INT 21h; position the cursor; set the attribute byte; write directly to B800h and A000h memory.
Read from the keyboard
Read keys with INT 16h and INT 21h, separate the scan code from the ASCII code, poll for a key without waiting, and take buffered line input.
Read the clock
Read the date and time from DOS as binary and from the RTC as packed BCD and print them; measure time with the tick counter in the BIOS data area.
Terminate a program
End a program properly with RET, INT 20h or INT 21h/4Ch; explain the difference between the COM and EXE templates.
Trace programs
Trace a program that uses services step by step and determine the state of the registers, flags, memory and screen at each step.

5.2.1BIOS and DOS services

5.2.1.1Service layers

Writing a single character to the screen means several separate jobs at the hardware level. The code of the character is written to the right cell of the video card's memory. The color byte of the cell is set. The new position of the cursor is reported to the controller on the video card through an I/O port. If the end of the line has been reached, output moves to the next line, and at the end of the screen all the lines are scrolled up by one. It is both laborious and dangerous for every program to do these jobs itself. When the video card changes, all the programs would have to be rewritten.

IBM PC compatible computers solve this problem with layers. Figure 5.2.1 shows four layers. At the bottom is the hardware: the video card, the keyboard controller, the disk and the clock. Hardware is reached directly through I/O ports (IN, OUT) and memory addresses. One level up is the BIOS. The BIOS routines know the details of the hardware and hide them behind a fixed interface. DOS, above it, offers more abstract services such as file, string, date and program management. At the top is the application program, which only calls these services.

Application programmov ah, 09h / int 21hDOS services: INT 20h, INT 21hfiles, strings, date/time, program endBIOS services: INT 10h, 13h, 16h, 1Ahdevice routines in ROMHardwarevideo card, keyboard controller, disk, clockdirect portaccess (IN/OUT)
Figure 5.2.1: The service layers. The application calls DOS with INT 21h and the BIOS with interrupts such as INT 10h, INT 16h and INT 1Ah. DOS has the BIOS do most of its work; the BIOS reaches the hardware with IN/OUT instructions and memory access.
Definition 5.2.1

The BIOS (Basic Input/Output System) is a collection of routines that live in the ROM on the motherboard and drive the hardware directly. It works without an operating system. When the computer is switched on, it tests the hardware, writes the addresses of its own routines into the interrupt vector table, and loads the operating system from the disk. DOS (Disk Operating System) is the operating system that runs on top of the BIOS and offers file, memory and program management.

The tool a program uses to reach a BIOS or DOS service is the software interrupt. The INT n instruction makes the processor read entry number n of the interrupt vector table in memory and branch to the address found there. The return address and flags are pushed on the stack; when the service routine finishes, it returns to the program with IRET. The subject here is not this mechanism itself but the services it offers. What matters is this: the program does not have to know the address of the service in memory. It knows only its number.

The benefit of using numbers instead of addresses is great. The BIOSes of different manufacturers place their routines at different addresses. Which version of DOS is loaded also changes the addresses. The vector table is filled at boot with the real addresses of that machine. So a program that says INT 10h reaches its own screen routine on every PC compatible machine. On the 8086, an INT n instruction takes 51 clock cycles; a direct far CALL takes 28. The cost is nearly twice the time, and the return is portability.

The same job can be done at different layers. There are three ways to write a character to the screen: DOS's INT 21h/02h service, the BIOS INT 10h/0Eh service, and writing directly to screen memory (segment B800h). The upper layer is more portable; its output can also be redirected to a file. The lower layer is faster and more flexible; it gives full control over color and position. A program chooses the layer according to the need and can mix layers in the same program.

5.2.1.2The service-call pattern

An interrupt number corresponds not to a single service but to a family of services. INT 21h does hundreds of jobs such as writing a character, writing a string, opening a file, reading the time and ending the program. Which job is to be done is decided by the number written to register AH before the interrupt. This number is called the service number or function number. Because AH is 8 bits wide, an interrupt can have at most 256 services.

Definition 5.2.2

The service-call pattern has four steps: (1) AH ← the service number; (2) the other parameters are written to registers such as AL, BX, CX, DX, DS:DX or ES:BP; (3) INT n is executed; (4) the result is read from registers (AL, AX, CX, DX) or flags (ZF, CF). Which register carries what is defined separately for each service.

The shortest example is making DOS print a letter on the screen:

mov ah, 02h    ; service: print char
mov dl, 'A'    ; parameter
int 21h        ; call DOS

The first line loads 02h into AH: DOS's "write character" service. The second line puts the ASCII code of the character to be written, 41h, into DL. This service expects the character in DL. The third line calls the interrupt. The processor reads the vector at address 0000:0084h (21h × 4 = 84h) and branches to the DOS routine. The routine writes the character where the cursor is, advances the cursor by one, and returns with IRET. The program continues from the instruction after int 21h.

What the processor does at the hardware level in this pattern is clear. MOV AH, 02h is a two-byte instruction (B4 02); the BIU takes it from the prefetch queue, the EU writes the register, and no memory bus cycle is needed. INT 21h, on the other hand, pushes three words on the stack (FLAGS, CS, IP) and reads two words from the vector table: five memory bus cycles. The service routine itself is hundreds of instructions. So even printing a single character takes thousands of clock cycles. This time is too short for the user to notice, but it becomes visible in a loop that fills the screen character by character.

Table 5.2.1 lists the frequently used interrupts and their providers.

Table 5.2.1: Frequently used BIOS and DOS interrupts.
InterruptProviderRole
INT 10hBIOSvideo: mode, cursor, character, string, pixel
INT 13hBIOSdisk
INT 16hBIOSkeyboard
INT 1AhBIOSclock counter, real-time clock
INT 20hDOSterminate the program (COM)
INT 21hDOShundreds of services: character and string I/O, files, date and time, exit

Services may change the registers they use. This is the most error-prone side of the pattern. For example INT 21h/02h puts the character in DL into AL on return; INT 21h/09h sets AL to 24h. A value kept in AL is lost after these calls. Values that will be needed later are kept in a register the service does not touch, or on the stack. Some services also use AL for a sub-selection. The VESA video card services are an example: in the service called with AX = 4F00h, AH = 4Fh selects the family and AL = 00h selects the job within that family.

Common mistake

Leaving a character that was read in AL and putting another INT 21h call in between. For example, a key is first read with AH = 01h, then AH = 02h, DL = 0Dh is called for a carriage return. This call makes AL 0Dh and the key that was read is lost. The value read must be copied to another register such as BL right after the call.

5.2.1.3ASCII and control characters

Every character written to the screen and read from the keyboard is a number. On the PC these numbers come from the ASCII (American Standard Code for Information Interchange) encoding. ASCII assigns characters to the codes 0–127. The codes 20h–7Eh are printable characters: space, digits, letters and punctuation. The codes 00h–1Fh are control characters. These carry meaning not as a shape on the screen but as an action.

Table 5.2.2: Frequently encountered control characters and their effect in INT 10h/0Eh and INT 21h/02h.
CodeNameEffect
07hBELbell
08hBScursor back one (character not erased)
09hTABtab (in DOS services)
0AhLFcursor down one line
0DhCRcursor to the start of the line; the code of the Enter key
1BhESCthe code of the Esc key

The codes of the printable characters are not randomly scattered; a few regularities make programs shorter. Table 5.2.3 summarizes them. The codes of the digits start at 30h: '0' = 30h, '9' = 39h. The numeric value of a digit is therefore found by subtracting 30h from its code. Conversely, a number from 0 to 9 becomes a printable digit when 30h is added. Uppercase letters are 41h–5Ah and lowercase letters 61h–7Ah. The difference between the two groups is exactly 20h, a single bit: bit 5. To convert a lowercase letter to uppercase, bit 5 is cleared (SUB AL, 20h or AND AL, 0DFh); to convert uppercase to lowercase, it is set (OR AL, 20h).

Table 5.2.3: Regularities in the ASCII table.
CharacterASCIIRelation
space20hthe first printable character
'0' … '9'30h–39hdigit = code − 30h
'A' … 'Z'41h–5Ahbit 5 = 0
'a' … 'z'61h–7Ahbit 5 = 1 (+20h)
'$'24hend of string in the INT 21h/09h service

Starting a new line takes two separate characters: CR (0Dh) and LF (0Ah). This distinction is a legacy of the typewriter. CR returns the print head to the start of the line; LF pushes the paper up one line. Figure 5.2.2 compares the three cases. If only CR is sent, the cursor returns to the start of the line and the next text lands on top of the same line. If only LF is sent, the cursor goes down one line but its column does not change; the text drifts to the right like a staircase. When both are sent together, the cursor comes to the start of the next line.

CR only (0Dh)ABCLF only (0Ah)ABCCR + LFABC
Figure 5.2.2: The effect of CR and LF. CR alone returns to the start of the line; LF alone goes down a line but keeps the column; CR LF together open a new line.

Letters outside the English alphabet (such as the Turkish ç, ğ, ı, ö, ş, ü) are not in 7-bit ASCII. DOS shows them with codes between 128 and 255, according to the active code page; for Turkish this page is CP857. The same byte may appear as a different letter in another code page. For this reason the example programs in the slides and in these notes use no such letters in strings: plain ASCII text only.

Example 5.2.1

AL = 37h ('7') and BL = 32h ('2') are two digit characters. To print their sum as a single digit, 30h is first subtracted from both: 07h and 02h. The sum is 09h. To print it, 30h is added: 39h = '9'. If the characters were added directly, 37h + 32h = 69h = 'i' would result. ASCII codes are names of characters, not numbers; they are converted to numbers before arithmetic.

5.2.2INT 10h: video services

5.2.2.1The service table and video modes

All the BIOS services related to the screen are gathered under INT 10h. Selecting the screen mode, moving the cursor, writing colored characters, printing a string in a single call, clearing a region of the screen and drawing pixels in graphics mode are all done with these services. Table 5.2.4 gives the most frequently used ones with their input and output registers.

Table 5.2.4: INT 10h video services.
AHServiceInputOutput / notes
00hset video modeAL = mode (03h: 80×25 color text)the screen is cleared
01hcursor shapeCH = start, CL = end scan lineCH = 20h → cursor hidden
02hset cursor positionBH = page, DH = row, DL = column–
03hget cursor positionBH = pageDH, DL = position; CH, CL = shape
06hscroll window upAL = number of lines (0 = clear), BH = attribute, CH,CL – DH,DL = cornersclears the screen or a window
09hwrite character and attributeAL = character, BH = page, BL = attribute, CX = repeat countcursor does not advance
0Ahwrite character onlyAL, BH, CXthe cell's attribute is kept
0Chwrite pixelAL = color, BH = page, CX = x, DX = yin graphics modes
0Ehteletype outputAL = character, BH = pagecursor advances; CR, LF, BS, BEL are interpreted
13hwrite stringAL = mode, BH, BL, CX = length, DH,DL = position, ES:BP = stringon AT and later BIOSes

The video card can work in different video modes. In text modes the screen is made of cells, each holding one character. In graphics modes the screen is made of pixels and the color of each pixel is written individually. The mode is selected with the AH = 00h service by giving the number in AL. Table 5.2.5 shows the frequently used modes and the segment at which the video memory starts.

Table 5.2.5: Frequently used video modes.
ALModeVideo memory
01h40×25 text, 16 colorsB800h
03h80×25 text, 16 colorsB800h
07h80×25 monochromeB000h
04h320×200 graphics, 4 colorsB800h
13h320×200 graphics, 256 colorsA000h

Selecting a mode also clears the screen. So the two lines often seen at the start of programs are the shortest way to get a clean 80×25 screen:

mov ah, 00h
mov al, 03h    ; or mov ax, 0003h
int 10h        ; clean 80×25 screen

AH and AL can be loaded together with a single MOV AX, 0003h instruction. Since AH is the high byte of AX it becomes 00h, and since AL is the low byte it becomes 03h. This three-byte instruction is both shorter and faster than two separate two-byte MOVs.

In mode 03h the screen is 25 rows and 80 columns (Figure 5.2.3). Rows are numbered from 0 to 24 and columns from 0 to 79. The top-left corner is (0, 0) and the bottom-right corner is (24, 79). In the BIOS services the row number is given in DH and the column number in DL. The emu8086 screen window is in this mode by default; it supports graphics modes only to a limited extent.

010203040506070790510152024(DH = 1, DL = 4)DL: column 0–79 →DHrow0–24
Figure 5.2.3: The 80×25 text screen. The row is given in DH (0–24) and the column in DL (0–79); the marked cell is the position (DH = 1, DL = 4).

5.2.2.2The cursor

The cursor is the position on the screen where the next character will be written. The BIOS keeps a cursor position for each display page. AH = 02h moves the cursor to row DH and column DL; AH = 03h reads the cursor position into DH and DL. Both services expect a display page number in BH. In 80×25 mode the video card's memory is large enough to hold several screens; VGA has 8 pages (0–7). Only one of the pages is visible. Page 0 is normally used.

Row and column can be loaded together with a single MOV DX instruction. mov dx, 0C28h puts 0Ch = 12 in DH and 28h = 40 in DL: the middle of the screen. The code below first moves the cursor to the middle, then reads the position and moves it one to the right.

; move the cursor to the middle
mov ah, 02h
mov bh, 0
mov dx, 0C28h  ; row 12, column 40
int 10h
; move the cursor one right
mov ah, 03h
mov bh, 0
int 10h        ; DH, DL = position
inc dl
mov ah, 02h
int 10h

The first four lines move the cursor to (12, 40). The next three lines read the position; on return DH = 12, DL = 40, and the shape of the cursor is written to CH, CL. INC DL makes the column 41. The last two lines write the new position. BH is not reloaded because it did not change after the 03h call. Figure 5.2.4 shows these steps and the cell's place in screen memory.

(12, 40) → (12, 41)DH = 0Ch = 12 (row), DL = 28h = 40 (column)read with 03h → inc dl → write with 02h: (12, 41)offset (12 × 80 + 40) × 2 = 07D0h
Figure 5.2.4: mov dx, 0C28h places the cursor at (12, 40); when the position read with 03h and incremented with inc dl is written with 02h, the cursor moves to (12, 41).

The cursor position is not merely a BIOS variable; it is also held in the video card's hardware. In color text mode, two registers of the display controller (the CRTC) determine in which cell the cursor blinks. The BIOS writes to these registers with OUT instructions through I/O ports 3D4h (index) and 3D5h (data). The AH = 02h call spares the program this port detail. The same position is also stored in the BIOS data area; characters written with INT 21h also start from this cursor position.

Every cell also has a place in screen memory. In mode 03h, 2 bytes are used per cell and the rows follow one another. The offset of the (row, column) cell is computed as follows:

offset = (row × 80 + column) × 2

For (12, 40) we get (960 + 40) × 2 = 2000 = 07D0h. For (1, 4) it is (80 + 4) × 2 = 168 = 00A8h. At the even address is the character's code, and at the odd address after it is its color.

5.2.2.3The attribute byte

In text mode the color of each cell is determined by one byte. This byte is called the attribute byte. Figure 5.2.5 shows the bits of the byte. The low four bits (bits 3–0) are the foreground, that is the color of the text. Bits 2–0 turn on the red, green and blue components; bit 3 makes the color brighter. Bits 6–4 are the color of the background: again red, green, blue. Bit 7 turns on blinking of the character.

B7R6G5B4I3R2G1B0blinkbackground RGBbrightforeground RGBExample: 1Eh = 0001 1110b → blue background, yellow (bright brown) text
Figure 5.2.5: The attribute byte: bit 7 blink, bits 6–4 background (RGB), bit 3 intensity, bits 2–0 foreground (RGB). 1Eh = 0001 1110b is yellow text on a blue background.
Definition 5.2.3

The attribute byte is the byte that determines the foreground and background color and the blinking of a character cell in text mode. Written in hexadecimal, the high digit gives the background and the low digit the foreground: attribute = background × 16 + foreground. If bit 7 = 1 the character blinks (depending on the BIOS setting, the background can instead be shown bright).

The sixteen colors come from all the combinations of four bits. Table 5.2.6 gives the numbers and names. The bright colors (8–F) are formed by adding bit 3 to their dark counterparts: 1 is blue, 9 light blue; 4 is red, C light red. Two exceptions stand out: 6 is brown, not yellow, and its bright version E is yellow. 7 is light gray and F is white.

Table 5.2.6: The sixteen colors of text mode.
No.ColorNo.Color
0black8dark gray
1blue9light blue
2greenAlight green
3cyanBlight cyan
4redClight red
5magentaDlight magenta
6brownEyellow
7light grayFwhite
Example 5.2.2

The default attribute is 07h: background 0 (black), foreground 7 (light gray). For white text on a blue background, background 1 and foreground F are chosen: 1 × 16 + 15 = 31 = 1Fh. Yellow text on a red background is 4Eh. 8Fh = 1000 1111b, because bit 7 is set, is blinking white text on a black background. Since only three bits are given to the background, a light green (A) background cannot be chosen directly: if A0h is written, the top 1 bit falls on bit 7 and blinking is turned on over a green background.

The attribute explorer in the slides produces the attribute byte and the INT 10h/09h call that uses it when a foreground and a background are selected. The same calculation is also easy by hand: the two color numbers are written side by side as two hexadecimal digits.

5.2.2.4Writing characters: 09h and 0Eh

INT 10h offers two main services for writing characters, and the two behave very differently. AH = 09h takes the character from AL and its color from BL, and writes the same character CX times side by side. It does not advance the cursor. AH = 0Eh is teletype output: it writes the character where the cursor is and advances the cursor by one. At the end of a line it moves to the next line, and on the last line it scrolls the screen up. It also interprets the characters CR, LF, BS and BEL as commands. Table 5.2.7 puts the differences side by side.

Table 5.2.7: Comparison of AH = 09h and AH = 0Eh.
FeatureAH = 09hAH = 0Eh (teletype)
InputsAL = character, BH = page, BL = attribute, CX = repeat countAL = character, BH = page
Coloryes (BL)none in text mode; the cell's color is kept
Cursordoes not advanceadvances; wraps to the next line at the end of a line
CR, LF, BS, BELprinted as symbols (♪, ◘ …)interpreted as commands
Screen scrollingnonethe screen scrolls up on the last line
Typical usecolored boxes, frames, the same character CX timesplain text flow
AH = 09h, AL = '*', CX = 3***cursor stayed at the startAH = 0Eh, AL = 'A'Acursor one to the right
Figure 5.2.6: 09h writes three stars but the cursor stays on the first cell; 0Eh writes 'A' and moves the cursor one to the right.

That 09h does not advance the cursor looks odd at first, but it suits the purpose of the service. To draw the top edge of a frame, the same character is written CX times side by side; the program decides where the cursor goes. There are two common ways to write colored plain text. In the first, each character is written in color with 09h and CX = 1, and then the cursor is moved one to the right with 02h. In the second, the whole string is written in a single call with 13h.

Common mistake

Writing characters one after another with 09h without moving the cursor. Each new character is written over the previous one and only the last is visible on the screen. After 09h the cursor is either advanced by hand with AH = 02h or the colored cell is written over with 0Eh.

5.2.2.5Code trace: mode, cursor, 09h and 0Eh

The following program uses four services one after another. First it clears the screen and moves the cursor to (1, 4), writes three yellow stars on a red background there, and then writes 'A' and 'B' with teletype. The purpose of the program is to show the difference between 09h and 0Eh in cursor and color handling in one place.

org 100h
mov ax, 0003h    ; AH=00h, AL=03h
int 10h          ; clears screen
mov ah, 02h      ; set cursor
mov bh, 0        ; page 0
mov dx, 0104h    ; DH=1, DL=4
int 10h
mov ah, 09h      ; char + attribute
mov al, '*'
mov bl, 4Eh      ; yellow on red
mov cx, 3        ; 3 times
int 10h          ; cursor stays!
mov ah, 0Eh      ; teletype
mov al, 'A'
int 10h          ; cursor moves
mov al, 'B'
int 10h
ret

The program is a .COM program: it begins with org 100h, and at the start the general registers are zero. The first two lines set mode 03h. The screen is cleared and the cursor comes to (0, 0). The next four lines move the cursor. The mov dx, 0104h instruction writes 01h to DH and 04h to DL. Because of the little-endian layout the bytes of the instruction are BA 04 01. After int 10h the cursor is at (1, 4) but there is nothing on the screen yet.

Then the 09h call is prepared. AL = 2Ah ('*'), BL = 4Eh, CX = 3 are loaded. BH is still 0; it does not need to be written again. After the call, the cells (1, 4), (1, 5) and (1, 6) hold yellow stars on a red background. The cursor, however, has not budged: it is still at (1, 4).

In the last part AH = 0Eh is loaded and 'A' is put in AL. INT 10h writes 'A' at (1, 4), where the cursor is; that is, over the first star. Then it moves the cursor to (1, 5). Because the 0Eh service does not change AH, only AL is changed for the second character. 'B' is written over the second star at (1, 5) and the cursor moves to (1, 6). AB* appears on the screen. Because 0Eh takes no attribute in text mode, 'A' and 'B' keep the color 4Eh left by the stars: yellow on red.

Table 5.2.8: Trace of the mode, cursor, 09h and 0Eh program (each row is the state after the instruction executes).
StepInstructionAXBXCXDXCursorExplanation
1mov ax, 0003h0003h0000h0000h0000h(0, 0)AH = 00h (set mode), AL = 03h (80×25 text)
2int 10h0003h0000h0000h0000h(0, 0)mode set, screen cleared, cursor at (0, 0)
3mov ah, 02h0203h0000h0000h0000h(0, 0)AH = 02h: set cursor position
4mov bh, 00203h0000h0000h0000h(0, 0)BH = page 0
5mov dx, 0104h0203h0000h0000h0104h(0, 0)DH = 1 (row), DL = 4 (column)
6int 10h0203h0000h0000h0104h(1, 4)cursor moved to (1, 4); screen empty
7mov ah, 09h0903h0000h0000h0104h(1, 4)AH = 09h: character + attribute
8mov al, '*'092Ah0000h0000h0104h(1, 4)AL = '*' = 2Ah
9mov bl, 4Eh092Ah004Eh0000h0104h(1, 4)BL = 4Eh: red background, yellow text
10mov cx, 3092Ah004Eh0003h0104h(1, 4)CX = 3 repeats
11int 10h092Ah004Eh0003h0104h(1, 4)*** in cells (1, 4)–(1, 6); cursor in place
12mov ah, 0Eh0E2Ah004Eh0003h0104h(1, 4)AH = 0Eh: teletype
13mov al, 'A'0E41h004Eh0003h0104h(1, 4)AL = 'A'
14int 10h0E41h004Eh0003h0104h(1, 5)'A' over the first star; cursor advanced
15mov al, 'B'0E42h004Eh0003h0104h(1, 5)AL = 'B'
16int 10h0E42h004Eh0003h0104h(1, 6)'B' over the second star: AB* on the screen
17ret0E42h004Eh0003h0104h(1, 6)0000h popped from the stack → IP
18INT 20h (PSP:0000h)0E42h004Eh0003h0104h(1, 6)the INT 20h in the PSP ends the program

The trace also shows how the BIOS services treat the registers. No call changed AX, BX, CX or DX; they changed only the screen and the cursor. Unlike the INT 21h services, these INT 10h services preserve AL. Even so, this assurance should not be relied on without looking at the documentation of each service. Read services such as AH = 03h deliberately change DX and CX on return.

5.2.2.6Writing strings: 13h

AH = 13h writes a string, in color, in a single call. It is found in the BIOS of the AT and later computers. It has many parameters: AL gives the write mode, BH the page, BL the attribute, CX the length of the string, DH and DL the starting position. The address of the string is in ES:BP. This differs from DOS's string service (DS:DX) and is often confused with it. No marker such as '$' is looked for at the end of the string; the length is taken from CX.

Table 5.2.9: The AH = 13h write modes (AL).
ALString formatCursor
00hcharacters only; all with the attribute in BLstays in place
01hcharacters only; all with the attribute in BLmoves to the end of the string
02hcharacter, attribute pairsstays in place
03hcharacter, attribute pairsmoves to the end of the string
org 100h
mov ax, 1301h    ; AH=13h, AL=01h
mov bx, 001Eh    ; BH=0, BL=1Eh
mov cx, 7        ; string length
mov dx, 0205h    ; row 2, col 5
lea bp, msg      ; ES:BP → string
int 10h
ret
msg db 'Welcome'

The program loads four register pairs with one instruction each. AX = 1301h means AH = 13h and AL = 01h: all characters in the color of BL, the cursor advances. BX = 001Eh is BH = 0 for the page and BL = 1Eh for the color; yellow text on a blue background. CX = 7 is the length of the string 'Welcome'. DX = 0205h puts the start at row 2, column 5. LEA BP, msg loads the offset of the string into BP.

The offset of the string is found from the byte counts of the preceding instructions. The four three-byte MOVs occupy 0100h–010Bh. emu8086 assembles the directly addressed LEA BP, msg instruction to the same three-byte code as MOV BP, OFFSET msg (BD 12 01); the instruction is at 010Ch–010Eh. The two-byte INT 10h is at 010Fh–0110h and the one-byte RET at 0111h. So msg starts at 0112h. In a .COM program all the segment registers point to the same value, so ES = DS and ES:BP points to the string correctly.

Table 5.2.10: Trace of the program that writes a colored string with AH = 13h.
StepInstructionAXBXCXDXBPCursorExplanation
1mov ax, 1301h1301h0000h0000h0000h0000h(0, 0)AH = 13h, AL = 01h (attribute in BL, cursor advances)
2mov bx, 001Eh1301h001Eh0000h0000h0000h(0, 0)BH = 0 (page), BL = 1Eh (blue background, yellow text)
3mov cx, 71301h001Eh0007h0000h0000h(0, 0)string length 7
4mov dx, 0205h1301h001Eh0007h0205h0000h(0, 0)DH = 2, DL = 5: starting position
5lea bp, msg1301h001Eh0007h0205h0112h(0, 0)BP = the offset of msg; ES = DS
6int 10h1301h001Eh0007h0205h0112h(2, 12)Welcome starting at (2, 5); cursor at (2, 12)
7ret1301h001Eh0007h0205h0112h(2, 12)program ends
8INT 20h (PSP:0000h)1301h001Eh0007h0205h0112h(2, 12)

The call writes Welcome into seven cells starting at (2, 5) and, because AL = 01h, moves the cursor to (2, 12): 5 + 7 = 12. With AL = 00h the string would still be written but the cursor would stay at (2, 5). If AL = 02h or 03h had been chosen, the string would have to carry its own attribute byte after each character; BL would then not be used, and CX would still be the number of characters.

Common mistake

Putting the string address in DS:DX for 13h and using DX twice. In this service DX is the position; if mov dx, offset msg is written, the position is spoiled, and BP points to some random place. Another mistake is to leave CX out and put '$' at the end of the string. 13h does not recognize '$'; it prints as many characters as CX says.

5.2.2.7Window scrolling and clearing the screen: 06h

AH = 06h scrolls a rectangular region of the screen, that is a window, up by AL lines. The lines vacated at the bottom of the window are painted with the space character in the BH attribute. If AL = 0 is given, instead of scrolling, the whole window is cleared. This feature is the standard way of clearing the screen without changing mode and in the color you want. AH = 07h does the same job downward.

Table 5.2.11: The registers of the AH = 06h service.
RegisterMeaning
ALnumber of lines to scroll; 0 = clear the window
BHattribute of the vacated lines
CH, CLtop-left corner (row, column)
DH, DLbottom-right corner (row, column)

The following program first clears the whole screen to a blue background, then opens a red box in the middle.

org 100h
mov ax, 0600h    ; AH=06h, AL=0
mov bh, 1Fh      ; blue/white
mov cx, 0000h    ; (0,0)
mov dx, 184Fh    ; (24,79)
int 10h
mov ax, 0600h
mov bh, 4Fh      ; red/white
mov cx, 0714h    ; (7,20)
mov dx, 103Bh    ; (16,59)
int 10h
ret

In the first call the corners are CX = 0000h and DX = 184Fh. Since 18h = 24 and 4Fh = 79, the window is the whole screen. BH = 1Fh gives the cleared cells a blue background and white text color. After the call, every cell of the screen holds the space character and the attribute 1Fh. Characters written afterwards, even with 0Eh, take this color. Selecting mode 03h again also clears the screen but returns the colors to the default 07h.

In the second call AX is made 0600h again. This is necessary because on some BIOSes INT 10h is not guaranteed to preserve AX. CX = 0714h makes the top-left corner (7, 20) and DX = 103Bh makes the bottom-right corner (16, 59). The box is 16 − 7 + 1 = 10 rows and 59 − 20 + 1 = 40 columns. Only this region is cleared to red; the outside stays blue. Neither call moves the cursor; after clearing, the cursor is moved to (0, 0) or into the box with AH = 02h.

Table 5.2.12: Trace of the program that clears the screen and a window with AH = 06h.
StepInstructionAXBXCXDXExplanation
1mov ax, 0600h0600h0000h0000h0000hAH = 06h (scroll up), AL = 0 (clear)
2mov bh, 1Fh0600h1F00h0000h0000hBH = 1Fh: blue background, white text
3mov cx, 0000h0600h1F00h0000h0000htop-left corner (0, 0)
4mov dx, 184Fh0600h1F00h0000h184Fhbottom-right corner (24, 79)
5int 10h0600h1F00h0000h184Fhthe whole screen is cleared to a blue background
6mov ax, 0600h0600h1F00h0000h184FhAH, AL again for the second call
7mov bh, 4Fh0600h4F00h0000h184FhBH = 4Fh: red background, white text
8mov cx, 0714h0600h4F00h0714h184Fhtop-left (7, 20)
9mov dx, 103Bh0600h4F00h0714h103Bhbottom-right (16, 59)
10int 10h0600h4F00h0714h103Bha 10-row × 40-column box is cleared to red
11ret0600h4F00h0714h103Bhprogram ends
AX0600hBH4FhCX0714hDX103BhCH,CL = (7, 20)DH,DL = (16, 59)(0,0)(24,79)
Figure 5.2.7: Diagram of the screen after the second call: the outer rectangle is the 80 × 25 screen cleared with 1Fh (blue background), the inner rectangle is the (7, 20)–(16, 59) window cleared with 4Fh (red background). The colors are not the real screen colors but the diagram's highlight colors.
Example 5.2.3

To clear the lower half of the screen (rows 13–24) to a black background, AX = 0600h and BH = 07h are loaded. The corners are CX = 0D00h (row 13, column 0) and DX = 184Fh (row 24, column 79). To scroll a region up by a single line, AL = 1 is given. With AX = 0601h, CX = 1400h, DX = 184Fh, the window of rows 20–24 scrolls up one line. Row 24 is vacated in the BH color.

5.2.3Direct access to video memory

5.2.3.1B800h text memory

INT 10h services always end up doing the same job: writing bytes to the video card's memory. This memory appears in the processor's address space like ordinary RAM. In the 8086's 1 MB address space the range A0000h–BFFFFh is reserved for video cards. In color text modes the video memory starts at physical address B8000h; a program reaches it with segment B800h. The video card's controller reads this memory from beginning to end dozens of times per second and draws each cell on the screen. A value written to memory appears on the screen on the next scan.

Definition 5.2.4

Video memory is the memory, mapped into the processor's address space, that holds the content the video card shows on the screen. In mode 03h it is 4000 bytes (80 × 25 × 2) starting at B800:0000h. Each cell occupies two bytes: at the even address the ASCII code of the character, at the odd address after it the attribute byte.

Writing directly to memory is much faster than calling the BIOS. An INT 10h call executes hundreds of instructions, while a direct write is a single MOV instruction. There is a price, though. A direct write does not move the cursor and does not update the cursor information the BIOS keeps. The output also does not go through DOS redirection. The program computes the cell address itself and must know which mode the video card is in. emu8086 supports this memory; the cells written appear in the screen window.

41hB800:00A8 · character 'A'4EhB800:00A9 · attributemov es:[di], ax (AX = 4E41h)low byte 41h → even address (character)
Figure 5.2.8: A screen cell is two bytes. When AX = 4E41h is written with mov es:[di], ax, the low byte 41h ('A') goes to the even address and the high byte 4Eh (the attribute) to the odd address.

Writing to a cell as a word places the character and its color in one instruction. The 8086 is little-endian: the low byte of a word is written to the lower address and the high byte to the higher address. That is why the character is put in the AL half of AX and the attribute in the AH half. Figure 5.2.8 shows this layout. Because the address of the word is even, the 8086 does this write in a single bus cycle: all 16 bits of the data bus are used, and the BHE and A0 lines are active together. Writing a word to an odd address would take two separate bus cycles.

5.2.3.2Code trace: writing to B800h

The following program first puts a yellow 'A' on a red background in cell (1, 4). Then, with REP STOSW, it fills the first three cells of the screen with the period character. In the form in the slides, the second part uses CX = 2000 to fill the whole screen; here CX = 3 so that it stays traceable.

org 100h
mov ax, 0B800h
mov es, ax
mov di, (1*80+4)*2  ; 00A8h
mov ax, 4E41h
mov es:[di], ax
xor di, di
mov ax, 072Eh
mov cx, 3           ; first 3 cells
cld
rep stosw
ret

The first two lines make ES B800h. An immediate value cannot be written directly into a segment register; there is no 8086 instruction MOV ES, 0B800h. So the value is first put into AX. The 0 at the start of the number is there so that the assembler does not take B800h for a name. The expression (1*80+4)*2 in the third line is evaluated at assembly time; only the result, 00A8h, goes into the machine code. No multiplication is done while the program runs.

MOV ES:[DI], AX names the ES segment explicitly. In a memory access with DI the default segment is DS; here DS points to the program's segment, so the segment prefix (the 26h byte) is mandatory. When the instruction runs, the physical address is B800h × 16 + 00A8h = B80A8h. 41h is written to this address and 4Eh to address B80A9h. The character appears on the screen at once, and the cursor stays where it was. According to the 8086 manual this instruction takes 9 + EA cycles; for [DI] the EA adds 5 cycles and the segment prefix adds 2: about 16 clock cycles. Writing the same character with INT 10h takes hundreds of times as long.

In the second part XOR DI, DI zeroes DI; this is one byte shorter than MOV DI, 0. AX = 072Eh means AL = 2Eh ('.') and AH = 07h (light gray). CLD clears the direction flag (DF), so the string instruction moves forward, increasing DI. In each iteration REP STOSW writes ES:[DI] ← AX, increases DI by 2 and decreases CX by 1; it stops when CX reaches zero. After three iterations DI = 0006h and CX = 0.

Table 5.2.13: Trace of the program that writes directly to screen memory.
StepInstructionAXCXDIESDFExplanation
1mov ax, 0B800hB800h0000h0000h0700h0the segment value goes into AX first
2mov es, axB800h0000h0000hB800h0ES = B800h: the segment of the text screen
3mov di, (1*80+4)*2B800h0000h00A8hB800h0(1 × 80 + 4) × 2 = 168 = 00A8h
4mov ax, 4E41h4E41h0000h00A8hB800h0AL = 41h ('A'), AH = 4Eh (attribute)
5mov es:[di], ax4E41h0000h00A8hB800h0B80A8h ← 41h, B80A9h ← 4Eh; 'A' on the screen at once
6xor di, di4E41h0000h0000hB800h0DI = 0: the top-left cell
7mov ax, 072Eh072Eh0000h0000hB800h0AL = 2Eh ('.'), AH = 07h
8mov cx, 3072Eh0003h0000hB800h0three cells will be filled
9cld072Eh0003h0000hB800h0DF = 0: DI moves forward
10rep stosw072Eh0000h0006hB800h0three times ES:[DI] ← AX, DI += 2
11ret072Eh0000h0006hB800h0program ends
ESB800hDI0006hAX072EhCX0000hB800:0000…2E072E072E07B800:00A8414Echaracter · attribute...Ascreen: rows 0–1, columns 0–5
Figure 5.2.9: Video memory when the program ends: three times 2E 07 starting at B800:0000h, and 41 4E at B800:00A8h. Three periods appear in the first row of the screen and an 'A' in the fifth column (column 4) of the second row.

To fill the whole screen, CX = 2000 is given: 80 × 25 cells. On the 8086 REP STOSW takes about 9 + 10 × CX clock cycles. For 2000 cells this is 20,009 cycles; on a 5 MHz processor about 4 ms. If the same job were done with 2000 separate INT 10h/0Eh calls, it would take dozens of times longer because of scrolling and cursor updates.

Common mistake

Putting the character and the attribute the wrong way round: if mov ax, 414Eh is written, the low byte 4Eh ('N') is the character and 41h is the color, blue text on a red background. In little-endian order the character is in AL and the attribute in AH. A second common mistake is writing MOV [DI], AX without setting ES. Without a segment prefix the write goes to the DS segment, that is, over the program's own data.

5.2.3.3Mode 13h and the pixel address

Mode 13h is VGA's graphics mode with 320 × 200 resolution and 256 colors. It is selected with mov ax, 0013h and int 10h. The greatest convenience of this mode for the programmer is the structure of the memory: each pixel is a single byte, and the pixels follow one another row by row. The video memory is 64,000 bytes (320 × 200) from A000:0000h to A000:F9FFh. The value of the byte is the color number of the pixel; the video card converts this number to a real color in a palette table. The first 16 colors of the default palette are the same as the text colors: 0Eh is yellow, 0Fh is white.

Each row is 320 = 140h bytes. The offset of pixel (x, y) is therefore computed as follows:

offset = y × 320 + x

For pixel (100, 50), 50 × 320 + 100 = 16,100 = 3EE4h. The last pixel (319, 199) is at 199 × 320 + 319 = 63,999 = F9FFh, the last byte of the memory. Figure 5.2.10 shows the offsets of the first rows and of the last row.

x=0x=1x=2x=3x=319y=00000000100020003013Fy=10140014101420143027Fy=2028002810282028303BFy=199F8C0F8C1F8C2F8C3F9FF…………⋮⋮offset = y·320 + x · orange diagonal: +141h
Figure 5.2.10: Pixel offsets in mode 13h. Each row is 140h bytes; the same column one row down is +140h, and one row down and one to the right on the diagonal is +141h further.

The BIOS offers a pixel service in this mode too. AH = 0Ch writes the color in AL to the pixel at column CX (x, 0–319) and row DX (y, 0–199); BH is the page and is 0 in mode 13h. AH = 0Dh reads the pixel's color into AL with the same CX, DX. Working with coordinates is easy, but one interrupt call per pixel is slow.

Example 5.2.4

The offset of pixel (160, 100) in the middle of the screen is 100 × 320 + 160 = 32,160 = 7DA0h; its physical address is A0000h + 7DA0h = A7DA0h. The top-right corner (319, 0) is at 013Fh, and the bottom-left corner (0, 199) is at 199 × 320 = 63,680 = F8C0h.

5.2.3.4Drawing a diagonal

A diagonal starting at the top-left corner is made of the pixels (0, 0), (1, 1), (2, 2) … First, the version that uses coordinates with the BIOS:

mov ax, 0013h
int 10h          ; 320×200, 256 colors
xor cx, cx       ; x = 0
xor dx, dx       ; y = 0
mov bh, 0        ; page
dot: mov ax, 0C0Eh  ; AH=0Ch, AL=yellow
int 10h
inc cx           ; one right
inc dx           ; one down
cmp dx, 200
jb dot           ; 200 pixels

The loop reloads AX on every iteration. The reason is that some BIOSes change AX in the 0Ch service; the safe way is to set AH and AL before every call. CX and DX increase together. When DX reaches 200 the JB does not jump and the loop ends having drawn 200 pixels. Since the screen is 320 pixels wide, the diagonal reaches the bottom edge, not the right edge.

The same line can also be drawn by writing directly to A000h memory. This time we work with offsets instead of coordinates:

mov ax, 0013h
int 10h
mov ax, 0A000h
mov es, ax
xor di, di       ; (0,0) → offset 0
mov al, 0Eh      ; yellow
mov cx, 200
draw: mov es:[di], al
add di, 141h     ; 320 + 1
loop draw
mov ah, 0
int 16h          ; wait for a key
mov ax, 0003h
int 10h          ; back to text mode

Why is 141h added? +140h (320) goes to the same column of the next row down, +1 to the next column right. Together they make 141h = 321 and give the next pixel on the diagonal. The last pixel (199, 199) is at 199 × 321 = 63,879 = F987h. For the opposite diagonal descending from the top-right corner, 13Fh (320 − 1) is added at each step. At the end the program waits for a key and then returns to text mode; this way the user can see the line and the DOS prompt does not stay on a graphics screen.

The speed difference between the two versions is large. In the direct version the loop body is three instructions: a memory write, an addition and LOOP. In the BIOS version an interrupt is called for every pixel, and the interrupt routine itself computes the address from the coordinates. emu8086's graphics support is limited: drawing with the 0Ch service is slow, and a direct write to A000h may not be visible in every version. In a PC emulator such as DOSBox both versions are fully visible.

To keep the trace short, the following program draws only four pixels and does not change the mode. It shows clearly that DI increases by 141h in each iteration of the loop.

org 100h
mov ax, 0A000h
mov es, ax
xor di, di       ; (0,0) → offset 0
mov al, 0Eh      ; yellow
mov cx, 4        ; first 4 pixels
draw: mov es:[di], al
add di, 141h     ; 320 + 1
loop draw
ret
Table 5.2.14: Trace of the program that draws a four-pixel diagonal in A000h memory.
StepInstructionALCXDIESExplanation
1mov ax, 0A000h00h0000h0000h0700hthe segment value goes through AX
2mov es, ax00h0000h0000hA000hES = A000h: the mode 13h video memory
3xor di, di00h0000h0000hA000hDI = 0: pixel (0, 0)
4mov al, 0Eh0Eh0000h0000hA000hcolor 0Eh (yellow)
5mov cx, 40Eh0004h0000hA000hfour pixels
6mov es:[di], al0Eh0004h0000hA000hA0000h ← 0Eh: pixel (0, 0)
7add di, 141h0Eh0004h0141hA000hone row down, one column right
8loop draw0Eh0003h0141hA000hCX = 3 ≠ 0: back to draw
9mov es:[di], al0Eh0003h0141hA000hA0141h ← 0Eh: pixel (1, 1)
12mov es:[di], al0Eh0002h0282hA000hA0282h ← 0Eh: pixel (2, 2)
15mov es:[di], al0Eh0001h03C3hA000hA03C3h ← 0Eh: pixel (3, 3)
16add di, 141h0Eh0001h0504hA000hDI = 0504h = the place of (4, 4)
17loop draw0Eh0000h0504hA000hCX = 0: the loop ends
18ret0Eh0000h0504hA000hprogram ends

The DI values in the table, 0000h, 0141h, 0282h, 03C3h and 0504h, are multiples of 321: 0, 321, 642, 963 and 1284. When each is written as y × 320 + x, it turns out that x = y; for example 963 = 3 × 320 + 3. When the loop ends, DI points to the place of the fifth pixel, (4, 4), which has not been drawn. The physical addresses are A0000h, A0141h, A0282h and A03C3h.

ESA000hDI0504hCX0000hAL0EhDI = 1284 → y = 4, x = 4320 = 140h bytes per row+141h = one down, one righttop-left of the screen (6 × 6 pixels)
Figure 5.2.11: The top-left 6 × 6 pixel region of the screen when the loop ends: (0, 0)–(3, 3) yellow, DI = 0504h (1284), that is y = 4, x = 4.

The pixel address explorer in the slides computes the (x, y) coordinates, offset and physical address of a point clicked on the screen. The diagonal and reverse-diagonal buttons animate the loop that adds 141h or 13Fh to DI.

5.2.4INT 16h: keyboard services

5.2.4.1Scan code and ASCII

When a key is pressed, the controller inside the keyboard sends a number that indicates the key's place on the keyboard. On the PC this number is read from I/O port 60h and, through the interrupt controller, gives rise to the IRQ 1 hardware interrupt. The BIOS keyboard interrupt routine (INT 09h) takes this number and finds its ASCII equivalent by looking at the state of Shift and Caps Lock. It then writes the two together as a word into the keyboard buffer in memory. The program reads keys from this buffer with INT 16h. This way keys pressed while the program is busy are not lost; they wait in line in the buffer.

Definition 5.2.5

The scan code is the code that indicates the physical position of the key pressed on the keyboard. The same key gives the same scan code whether or not Shift is held: 1Eh for 'a' and 'A'. The ASCII code, on the other hand, indicates the key's current meaning, that is, the character produced: 61h for 'a', 41h for 'A'.

Table 5.2.15: INT 16h keyboard services.
AHServiceOutput
00hwait for a key and read itAH = scan code, AL = ASCII; the key is removed from the buffer
01his a key available? (does not wait)ZF = 1: no key · ZF = 0: AX = key; the key is not removed from the buffer
02hShift statesAL bits: 0 right Shift, 1 left Shift, 2 Ctrl, 3 Alt, 4 Scroll Lock, 5 Num Lock, 6 Caps Lock, 7 Insert

AH = 00h waits until a key is pressed if there is no key in the buffer. When a key arrives, it puts the scan code in AH and the ASCII code in AL and removes the key from the buffer. The key is not echoed on the screen; if something is to be seen on the screen, the program writes it itself. Table 5.2.16 lists the values returned by some keys.

Table 5.2.16: INT 16h/00h return values of some keys (IBM PC/AT, US layout).
KeyAH (scan)AL (ASCII)KeyAH (scan)AL
a / A1Eh61h / 41h↑ / ↓48h / 50h00h
102h31h← / →4Bh / 4Dh00h
Enter1Ch0DhF1 … F103Bh … 44h00h
Esc01h1BhBackspace0Eh08h
Space39h20hCtrl+C2Eh03h

Keys such as the arrow keys, function keys, Home and End have no ASCII equivalent. These are called extended keys, and INT 16h returns AL = 00h for them. The program looks at AL first; if AL is zero, it recognizes the key from the scan code in AH. The F1 key, for example, gives AH = 3Bh, AL = 00h. Letters pressed with Ctrl fall into the first 32 codes of ASCII: Ctrl+A = 01h, Ctrl+C = 03h. The code is the low five bits of the letter's code.

The job of the MOV AH, 0 · INT 16h pair often seen at the end of programs is simple. The program waits for a key, so that the output screen can be read before it closes. The keyboard explorer in the slides shows which AH and AL values INT 16h/00h would return for a key that is pressed.

5.2.4.2Code trace: read a key, print it in uppercase

The following program reads keys until Enter is pressed. It converts lowercase letters to uppercase and writes them, and writes other characters as they are. The program uses together the fact that INT 16h does not echo and the bit 5 rule of the ASCII layout.

org 100h
read:
mov ah, 0        ; wait for key
int 16h          ; AH=scan, AL=ASCII
cmp al, 0Dh      ; Enter?
je done
cmp al, 'a'
jb echo
cmp al, 'z'
ja echo
sub al, 20h      ; lower → upper
echo:
mov ah, 0Eh
int 10h          ; print it
jmp read
done:
ret

The loop starts at the read label. INT 16h waits for a key. CMP AL, 0Dh checks for Enter; if equal, JE ends the program. Then two comparisons test whether AL is in the range 'a'–'z'. JB and JA are unsigned comparison jumps: JB jumps when CF = 1; JA jumps when CF = 0 and ZF = 0. If AL is below 'a' or above 'z', it is not a letter, so control goes straight to echo. If it is inside the range, SUB AL, 20h clears bit 5. The echo part writes the character with teletype and the loop returns to the start.

The user presses Shift+o, k and Enter in turn. Table 5.2.17 gives the important steps; similar steps in the same iteration are skipped.

Table 5.2.17: Trace of the program that reads keys and prints them in uppercase (keys pressed: Shift+o, k, Enter).
StepInstructionAXCFZFScreen (output)Explanation
1mov ah, 00000h00–AH = 00h: wait for a key and read it
2int 16h184Fh00–Shift+o: AH = 18h (scan), AL = 4Fh ('O')
3cmp al, 0Dh184Fh00–4Fh − 0Dh: the result is not zero
4je done184Fh00–not Enter, no jump
5cmp al, 'a'184Fh10–4Fh < 61h: borrow, CF = 1
6jb echo184Fh10–CF = 1: jump to echo
7mov ah, 0Eh0E4Fh10–AH = 0Eh; 'O' is still in AL
8int 10h0E4Fh10OO on the screen
9jmp read0E4Fh10Oback to the start of the loop
11int 16h256Bh10Ok: AH = 25h, AL = 6Bh
14cmp al, 'a'256Bh00O6Bh ≥ 61h: CF = 0
15jb echo256Bh00Ono jump: may be a lowercase letter
16cmp al, 'z'256Bh10O6Bh − 7Ah: borrow, CF = 1, ZF = 0
17ja echo256Bh10OJA needs CF = 0 and ZF = 0; it does not jump
18sub al, 20h254Bh00O6Bh − 20h = 4Bh = 'K'
20int 10h0E4Bh00OKK on the screen
23int 16h1C0Dh00OKEnter: AH = 1Ch, AL = 0Dh
24cmp al, 0Dh1C0Dh01OK0Dh − 0Dh = 0: ZF = 1
25je done1C0Dh01OKjump to done
26ret1C0Dh01OKprogram ends

On the first key AL = 4Fh ('O') arrives. CMP AL, 'a' computes 4Fh − 61h; the result is negative, a borrow is needed and CF = 1. JB jumps: the character is not a lowercase letter and is written as it is. On the second key AL = 6Bh ('k') arrives. 6Bh − 61h needs no borrow, CF = 0 and JB does not jump. 6Bh − 7Ah, however, needs a borrow: CF = 1, ZF = 0. For JA to jump both CF and ZF would have to be zero; it does not jump. So it is settled that AL lies in the range 61h ≤ AL ≤ 7Ah. SUB AL, 20h turns 6Bh into 4Bh, that is 'K'. The 0Dh that arrives with Enter sets ZF = 1 in the first comparison and the program ends.

One more detail can be seen in the AX column of the table. Before the teletype call AH = 0Eh is set; at the start of the loop MOV AH, 0 clears AH again, but AL keeps the last character written. When INT 16h returns, both AH and AL change with the new key. In the end OK appears on the screen. Because Enter itself is not echoed, the cursor stays on the line.

5.2.4.3Polling without waiting

AH = 00h stops the program until a key arrives. A game or an animation, however, must keep working while it waits for a key. For this AH = 01h is used: the service returns at once and reports with ZF whether there is a key. If ZF = 1 there is no key in the buffer. If ZF = 0 there is a key and it is in AX, but it is not removed from the buffer. To actually take the key, the program then calls AH = 00h. Asking about the state of a device again and again in a loop is called polling.

org 100h
xor dx, dx       ; work counter
poll:
inc dx           ; background work
mov ah, 01h      ; key ready?
int 16h          ; ZF=1 → none
jz poll
mov ah, 00h      ; take the key
int 16h
ret

DX stands for the work done while waiting; it increases by one on each iteration. In a real program an animation frame would be drawn here or a calculation advanced. In the trace there is no key at the first two polls, and at the third the user has pressed the x key.

Table 5.2.18: Trace of the loop that polls for a key with AH = 01h (x is pressed at the third poll).
StepInstructionAXDXZFExplanation
1xor dx, dx0000h0000h1the work counter is zeroed
2inc dx0000h0001h0background work: 1
3mov ah, 01h0100h0001h0AH = 01h: is a key available?
4int 16h0100h0001h1buffer empty: ZF = 1
5jz poll0100h0001h1ZF = 1: back to poll
6inc dx0100h0002h0background work: 2
8int 16h0100h0002h1still no key
10inc dx0100h0003h0background work: 3
12int 16h2D78h0003h0x is there: ZF = 0, AX = 2D78h; the key stays in the buffer
13jz poll2D78h0003h0ZF = 0: leave the loop
14mov ah, 00h0078h0003h0AH = 00h: take the key
15int 16h2D78h0003h0the same key is read and removed from the buffer
16ret2D78h0003h0program ends

In the first two iterations INT 16h returns ZF = 1 and JZ continues the loop. The program does not freeze: DX increases on each iteration. In the third iteration a key has arrived. INT 16h makes ZF = 0 and puts 2D78h in AX: scan code 2Dh, ASCII 78h ('x'). The key stays in the buffer. JZ does not jump and the loop is left. AH = 00h reads the same key and this time removes it from the buffer; AX is again 2D78h. At the end of the program DX = 3: the background work was done three times while waiting for the key.

Common mistake

Seeing the key with 01h and not taking it with 00h. Because 01h does not remove the key from the buffer, the same key still looks "available" on the next iteration of the loop; the program reacts to a single key endlessly. After responding to the key, the buffer is emptied with AH = 00h.

5.2.5INT 21h: DOS character and string services

5.2.5.1Frequently used services

INT 21h is DOS's main service interrupt. Of its hundreds of services, character and string I/O, date, time and program termination are the most used. Table 5.2.19 summarizes them.

Table 5.2.19: Frequently used INT 21h services.
AHServiceInputOutput
01hread a character and echo it–AL = character
02hwrite a characterDL = characterAL = DL
07h / 08hread a character, without echo–AL (08h checks for Ctrl+C)
09hwrite a stringDS:DX → string ending with '$'AL = 24h
0Ahread a buffered lineDS:DX → buffer[buffer+1] = count, buffer+2 = text
2Ahget the date–CX = year, DH = month, DL = day, AL = day of the week (0 = Sunday)
2Chget the time–CH = hour, CL = minute, DH = second, DL = hundredths
2Bh / 2Dhset the date / timesame registers as 2Ah / 2ChAL = 00h success
4Chterminate the programAL = exit code(does not return)

An important difference between DOS services and BIOS services is that they obey I/O redirection. If the program is run as program > output.txt, everything written with 02h and 09h goes to the file instead of the screen. The BIOS's INT 10h output always goes to the screen; DOS cannot see it. Similarly, 01h and 0Ah can take their input from a file.

5.2.5.2INT 10h/0Eh or INT 21h/02h?

The two services that write a single character to the screen look very similar. Both write the character where the cursor is and advance the cursor; both interpret control characters such as CR and LF. Their differences come from the layer they work at. Table 5.2.20 compares them.

Table 5.2.20: Comparison of INT 10h/0Eh and INT 21h/02h.
FeatureBIOS · INT 10h, AH = 0EhDOS · INT 21h, AH = 02h
Characterin ALin DL
Software neededonly the video BIOS; also works in boot codeDOS must be loaded
Redirectionno; always to the screenyes; to a file, to a printer
Colorin graphics mode with BLnone
AL on returnpreservedAL = DL
Ctrl+Break checknoneyes

The choice depends on the environment the program will run in. A boot loader runs before DOS, so it can use only the BIOS. A tool whose output is to be saved to a file must choose the DOS service. The two can be mixed in the same program; both use the same cursor position kept by the BIOS.

5.2.5.3Code trace: read and write a character

The following program reads a character from the keyboard, moves to a new line, and writes the letter after the character that was read. Although short, it shows clearly how AL gets clobbered between services.

org 100h
mov ah, 01h      ; read + echo
int 21h          ; AL = char
mov bl, al       ; save it
mov ah, 02h      ; write char
mov dl, 0Dh      ; CR: line start
int 21h
mov dl, 0Ah      ; LF: next line
int 21h
inc bl           ; next letter
mov dl, bl
int 21h
ret
Table 5.2.21: Trace of the program that reads a character and writes the next one on a new line (key pressed: k). ⏎ means CR, ↵ means CR LF.
StepInstructionAXBXDXScreen (output)Explanation
1mov ah, 01h0100h0000h0000h–AH = 01h: read and echo
2int 21h016Bh0000h0000hkk: AL = 6Bh; k on the screen
3mov bl, al016Bh006Bh0000hkthe character read is saved in BL
4mov ah, 02h026Bh006Bh0000hkAH = 02h: write DL
5mov dl, 0Dh026Bh006Bh000DhkDL = 0Dh (CR)
6int 21h020Dh006Bh000Dhk⏎cursor to the start of the line; AL = 0Dh
7mov dl, 0Ah020Dh006Bh000Ahk⏎DL = 0Ah (LF)
8int 21h020Ah006Bh000Ahk↵cursor to the next line; AL = 0Ah
9inc bl020Ah006Ch000Ahk↵BL = 6Ch ('l')
10mov dl, bl020Ah006Ch006Chk↵DL = 'l'
11int 21h026Ch006Ch006Chk↵ll on the screen; AL = 6Ch
12ret026Ch006Ch006Chk↵lprogram ends

AH = 01h waits for a key and echoes it on the screen; when the user presses k, k appears on the screen and AL = 6Bh. The value read is copied to BL at once, because the following INT 21h calls will change AL. Indeed, after CR is written AL = 0Dh, and after LF is written AL = 0Ah. The 02h service puts DL into AL on return. AH stays 02h, so it is enough to load it once for the three calls. CR takes the cursor to the start of the line and LF to the next line. INC BL turns 6Bh into 6Ch, 'k' into 'l', and the last call writes this letter on the new line. The final state of the screen is two lines: the echoed k above, l below.

5.2.5.4Code trace: printing a string

AH = 09h writes the string pointed to by DS:DX until it sees the '$' (24h) character. '$' is the terminator; it is not written itself. The 0Dh and 0Ah inside the string end the line, that is, control characters are interpreted here too.

Definition 5.2.6

A '$'-terminated string is the format expected by DOS's 09h service: the characters sit one after another in memory and the string ends at the first 24h byte. The length is not given separately. The service sets AL to 24h on return.

org 100h
mov dx, offset msg1  ; DS:DX → string
mov ah, 09h
int 21h
mov dx, offset msg2
int 21h              ; AH still 09h
ret
msg1 db 'Welcome, 8086!', 0Dh, 0Ah, '$'
msg2 db 'Good-bye!$'

The code part is 13 bytes (0100h–010Ch). So msg1 starts at 010Dh. msg1 is 14 characters plus CR, LF and '$', 17 bytes; msg2 is at 010Dh + 17 = 011Eh. The OFFSET operator gives the offset of the variable, not its contents.

Table 5.2.22: Trace of the program that writes two strings with AH = 09h.
StepInstructionAXDXScreen (output)Explanation
1mov dx, offset msg10000h010Dh–DS:DX → msg1 (010Dh)
2mov ah, 09h0900h010Dh–AH = 09h
3int 21h0924h010DhWelcome, 8086!↵written up to the '$'; AL = 24h
4mov dx, offset msg20924h011EhWelcome, 8086!↵DX → msg2 (011Eh)
5int 21h0924h011EhWelcome, 8086!↵Good-bye!AH is still 09h: the second string
6ret0924h011EhWelcome, 8086!↵Good-bye!program ends

The first call writes Welcome, 8086! and moves to a new line with CR LF. AL = 24h. Before the second call only DX is changed; AH is still 09h. Even so, loading AH before every call is a good habit against the risk that a line added to the program later spoils AH. The output is two lines. The '$' character itself cannot be printed with this service; to print it, the 02h service with DL = 24h is used.

Common mistake

Forgetting to put '$' at the end of the string. 09h writes whatever it finds in memory until it finds the first 24h byte: the program's code, other variables, random bytes. The screen fills with garbage, and the bell may even ring because of control characters. The reverse also happens: the string 'Price: 5$ TL$' is written only as Price: 5, because the first '$' ends the string.

5.2.5.5Buffered line input

Getting a name or a number from the user takes more than reading keys one by one. When the user types something wrong they erase it with Backspace, and when they press Enter the line is finished. AH = 0Ah has DOS do this editing. The program only prepares a buffer and puts its address in DS:DX. DOS reads keys until Enter is pressed, echoes them, and allows correction with Backspace and Esc. The program does not run in the meantime; the call returns when the line is finished.

Definition 5.2.7

The 0Ah buffer has three parts. In byte 0 the program writes the capacity: the maximum number of characters to be accepted, Enter included. In byte 1 DOS writes the number of characters read (Enter is not counted). The text begins at byte 2 and the code of Enter, 0Dh, is appended to its end. The capacity cannot be 0.

Figure 5.2.12 shows the state after Ali is typed and Enter is pressed in a buffer defined as buffer db 10, ?, 10 dup(?). Byte 0 = 0Ah (10 characters), byte 1 = 03h, then 'A', 'l', 'i' and 0Dh. The text does not end with '$'; to print it with 09h, the program puts '$' in place of 0Dh. When the buffer is full, DOS does not accept further keys and the bell rings; only Enter and Backspace keep working.

0Ah+003h+1'A'+2'l'+3'i'+40Dh+5?+6at mostreadcharacters …DS:DX →
Figure 5.2.12: The 0Ah buffer after Enter: +0 capacity (0Ah), +1 number read (03h), the text from +2 and 0Dh at the end.

The following program reads the user's name and greets them.

org 100h
mov dx, offset buffer
mov ah, 0Ah          ; buffered input
int 21h
mov bl, [buffer+1]   ; count read
mov bh, 0
mov byte ptr buffer[bx+2], '$'
mov dx, offset greet
mov ah, 09h
int 21h
lea dx, [buffer+2]
int 21h
ret
buffer db 10, ?, 10 dup(?)
greet  db 0Dh, 0Ah, 'Hello $'
Table 5.2.23: Trace of the program that reads a name and greets (typed: Ali, Enter).
StepInstructionAXBXDXScreen (output)Explanation
1mov dx, offset buffer0000h0000h011Fh–DS:DX → buffer (011Fh)
2mov ah, 0Ah0A00h0000h011Fh–AH = 0Ah: read a line
3int 21h0A00h0000h011FhAli⏎buffer = 0Ah, 03h, 'A', 'l', 'i', 0Dh
4mov bl, [buffer+1]0A00h0003h011FhAli⏎BL = [0120h] = 3
5mov bh, 00A00h0003h011FhAli⏎BX = 0003h
6mov byte ptr buffer[bx+2], '$'0A00h0003h011FhAli⏎[011Fh + 3 + 2] = [0124h] ← '$'
7mov dx, offset greet0A00h0003h012BhAli⏎DX → greet (012Bh)
8mov ah, 09h0900h0003h012BhAli⏎AH = 09h
9int 21h0924h0003h012BhAli⏎↵Hello CR LF and Hello are written
10lea dx, [buffer+2]0924h0003h0121hAli⏎↵Hello DX = 0121h: the start of the text
11int 21h0924h0003h0121hAli⏎↵Hello AliAli is written
12ret0924h0003h0121hAli⏎↵Hello Aliprogram ends

The program's code is 31 bytes (0100h–011Eh). emu8086 assembles the directly addressed LEA DX, [buffer+2] instruction to the same three-byte code as MOV DX, OFFSET buffer+2 (BA 21 01); buffer therefore starts at 011Fh and greet at 012Bh. When the call returns, the buffer holds the bytes 0A 03 41 6C 69 0D from 011Fh. MOV BL, [buffer+1] takes the number read, 3. BH is zeroed because the number will be used as BX in the address calculation. The address buffer[bx+2] is 011Fh + 3 + 2 = 0124h; exactly the byte where 0Dh sits. '$' is written there and the text can now be printed with 09h. The BYTE PTR specifier is here for clarity. Because buffer is defined with DB, the assembler already knows the write is a byte; in an address that has no variable name, such as [BX+2], the specifier is mandatory.

Then greet is written: because it starts with CR LF, the output moves to a new line and Hello is printed. Since Enter itself echoed only CR, the cursor was at the start of the line; the LF takes it down to the next line. LEA DX, [buffer+2] loads the start of the text, 0121h, into DX. Since AH is still 09h, the last call writes Ali. Hello Ali appears on the screen.

Example 5.2.5

In a buffer defined as buffer db 6, ?, 6 dup(?), the user types Micro12 and presses Enter. Because the capacity is 6 including Enter, at most 5 characters are accepted. 'M', 'i', 'c', 'r', 'o' are accepted; the bell rings at the keys '1' and '2'. When Enter arrives, the buffer becomes 06 05 4D 69 63 72 6F 0D. The number read is 5; '$' is written at address buffer + 5 + 2 = buffer + 7 and only Micro is printed on the screen.

Common mistake

Not setting the first byte of the buffer, or reading the text from buffer+0. If the capacity is left 0, the service behaves unpredictably. The text always starts at buffer+2; buffer+0 and buffer+1 are numbers, and if they are written to the screen meaningless characters appear.

5.2.6Date and time

5.2.6.1AH = 2Ah and AH = 2Ch

DOS provides the system's date and time through two services. AH = 2Ah returns the date and AH = 2Ch the time. Table 5.2.24 shows the return registers. All the values are binary numbers. If the hour is 14, CH = 0Eh; if the minute is 35, CL = 23h. The year fits in the 16-bit CX: 2026 = 07EAh.

Table 5.2.24: Return values of INT 21h/2Ah and 2Ch.
RegisterAH = 2Ah (date)AH = 2Ch (time)
CX / CHCX = year (e.g. 07EAh = 2026)CH = hour (0–23)
CL(part of CX)CL = minute (0–59)
DHmonth (1–12)second (0–59)
DLday (1–31)hundredths (0–99)
ALday of the week (0 = Sunday … 6 = Saturday)–

To write binary values on the screen, each number is split into its decimal digits. For a number between 0 and 99 the shortest way is the AAM instruction. AAM divides AL by 10; it writes the quotient to AH and the remainder to AL. For 14, AH = 1 and AL = 4. Then 30h is added to the two digits and ASCII digits are obtained. For numbers greater than 99, such as the year, repeated division by 10 is used. The BIOS INT 1Ah/02h service, on the other hand, gives the time not in binary but as BCD, and AAM is not used there.

Example 5.2.6

AAM runs with AL = 23h (35): 35 ÷ 10 = 3, remainder 5. AH = 03h, AL = 05h, that is AX = 0305h. ADD AX, 3030h converts both bytes to ASCII at once: AX = 3335h, AH = '3', AL = '5'. When AH and then AL are written, 35 appears on the screen. For AL = 07h, AX = 0007h → 3037h, and 07 appears on the screen: AAM adds the leading zero to single-digit values by itself.

5.2.6.2Code trace: printing the day name

The day of the week arrives in AL as a number from 0 to 6. The natural way to turn it into a name is a lookup table: the names of the days are laid out one after another in memory with equal lengths, and AL is converted to a position in the table. In the program below each name is 4 bytes including '$'; so the position is AL × 4.

org 100h
mov ah, 2Ah
int 21h          ; AL = 0…6
mov ah, 0
mov bl, 4
mul bl           ; AX = AL × 4
mov dx, offset days
add dx, ax
mov ah, 09h
int 21h
ret
days db 'Sun$Mon$Tue$Wed$'
     db 'Thu$Fri$Sat$'

The date comes from the system clock; the trace is for Wednesday, January 7, 2026. On return from INT 21h, CX = 07EAh (2026), DH = 01h (January), DL = 07h and AL = 3 (Wednesday). DX is 0107h at this moment. MOV AH, 0 makes AX 0003h. MUL BL multiplies AL by BL and writes the 16-bit result to AX: 3 × 4 = 12 = 000Ch. This is the distance of the name Wed$ from the start of the table.

MOV DX, OFFSET days erases the date in DX and loads the offset of the table, 0114h. If the date were needed later, it would have to be saved before this line. ADD DX, AX gives 0114h + 000Ch = 0120h: the first byte of Wed$. With AH = 09h, Wed is printed on the screen.

Table 5.2.25: Trace of the program that prints the day name from a table (date Wednesday, January 7, 2026).
StepInstructionAXBXCXDXScreen (output)Explanation
1mov ah, 2Ah2A00h0000h0000h0000h–AH = 2Ah: get the date
2int 21h2A03h0000h07EAh0107h–CX = 07EAh (2026), DH = 01h (month), DL = 07h (day), AL = 3 (Wednesday)
3mov ah, 00003h0000h07EAh0107h–AX = 0003h
4mov bl, 40003h0004h07EAh0107h–each name is 4 bytes
5mul bl000Ch0004h07EAh0107h–AX = 3 × 4 = 12 = 000Ch
6mov dx, offset days000Ch0004h07EAh0114h–DX = days = 0114h; the date is erased
7add dx, ax000Ch0004h07EAh0120h–DX = 0120h: Wed$
8mov ah, 09h090Ch0004h07EAh0120h–AH = 09h
9int 21h0924h0004h07EAh0120hWedWed on the screen
10ret0924h0004h07EAh0120hWedprogram ends
AL0ChBL04hAX000ChDX0120hdays (0114h): 7 × 4 bytesSun$+0Mon$+4Tue$+8Wed$+12Thu$+16Fri$+20Sat$+24DXscreen▌
Figure 5.2.13: After ADD DX, AX: DX = 0120h points to byte +12 of the days table, that is, to Wed$.

The code part is 20 bytes, so days starts at 0114h. The lengths of the instructions: MOV AH, imm 2, INT 2, MOV BL, imm 2, MUL BL 2, MOV DX, imm 3, ADD DX, AX 2, RET 1 byte. Two left shifts (SHL AX, 1 twice) could have been used instead of the multiplication, because 4 is a power of two. On the 8086 MUL takes 70–77 clock cycles, while two SHLs take only 4.

Common mistake

Skipping the MOV AH, 0 line. In this program it does no harm, because MUL BL rewrites all of AX. But if the multiplication were done with two SHL AX, 1, the 2Ah left in AH would shift too: AX = 2A03h → A80Ch. DX = 0114h + A80Ch = A920h and 09h would print some unrelated place in memory. When computing a table position, the high half of AX must always be zeroed.

5.2.6.3Code trace: printing the time

To write the time as HH:MM, two numbers are printed in the same way. The repeated part is put into a procedure: print2 writes the number from 0 to 99 in AL as two digits.

org 100h
mov ah, 2Ch      ; get system time
int 21h          ; CH=hour CL=min
mov al, ch
call print2
mov dl, ':'
mov ah, 02h
int 21h
mov al, cl
call print2
ret
print2:          ; AL (0-99) → 2 digits
aam              ; AH=tens AL=ones
add ax, 3030h    ; ASCII
mov bx, ax
mov dl, bh
mov ah, 02h
int 21h
mov dl, bl
int 21h
ret

The trace is for the time 14:35:07.42. On return from INT 21h, CX = 0E23h (CH = 14, CL = 35) and DX = 072Ah (DH = 7 seconds, DL = 42 hundredths). CALL print2 pushes the return address, the address of the instruction after call, 0109h, on the stack; SP drops from FFFEh to FFFCh. Inside the procedure AAM splits 14 into 1 and 4, and ADD AX, 3030h converts to ASCII.

The MOV BX, AX line is the key point of the procedure. The two digits are in AH and AL, but the first INT 21h/02h call will put DL into AL and erase the ones digit. So both are copied to BX and taken in turn from BH and BL into DL. The minute in CL, on the other hand, is not spoiled by any call: the procedure does not touch CX, and the 02h service does not change CX. The minute is safely taken with MOV AL, CL.

Table 5.2.26: Trace of the program that writes the time as HH:MM (time 14:35:07.42).
StepInstructionAXBXCXDXSPScreen (output)Explanation
1mov ah, 2Ch2C00h0000h0000h0000hFFFEh–AH = 2Ch: get the time
2int 21h2C00h0000h0E23h072AhFFFEh–CH = 0Eh (14), CL = 23h (35), DH = 07h, DL = 2Ah (42)
3mov al, ch2C0Eh0000h0E23h072AhFFFEh–AL = hour
4call print22C0Eh0000h0E23h072AhFFFCh–return address 0109h on the stack
5aam0104h0000h0E23h072AhFFFCh–14 = 1 × 10 + 4: AH = 1, AL = 4
6add ax, 3030h3134h0000h0E23h072AhFFFCh–two digits to ASCII: '1', '4'
7mov bx, ax3134h3134h0E23h072AhFFFCh–saved in BX; 02h clobbers AL
8mov dl, bh3134h3134h0E23h0731hFFFCh–DL = '1'
9mov ah, 02h0234h3134h0E23h0731hFFFCh–AH = 02h
10int 21h0231h3134h0E23h0731hFFFCh11 on the screen; AL = 31h
11mov dl, bl0231h3134h0E23h0734hFFFCh1DL = '4'
12int 21h0234h3134h0E23h0734hFFFCh144 on the screen
13ret0234h3134h0E23h0734hFFFEh14return to 0109h
14mov dl, ':'0234h3134h0E23h073AhFFFEh14DL = ':'
16int 21h023Ah3134h0E23h073AhFFFEh14:: on the screen
17mov al, cl0223h3134h0E23h073AhFFFEh14:AL = minute = 23h; CL not clobbered
18call print20223h3134h0E23h073AhFFFCh14:return address 0114h
19aam0305h3134h0E23h073AhFFFCh14:35 = 3 × 10 + 5
20add ax, 3030h3335h3134h0E23h073AhFFFCh14:'3', '5'
24int 21h0233h3335h0E23h0733hFFFCh14:33 on the screen
26int 21h0235h3335h0E23h0735hFFFCh14:355 on the screen
27ret0235h3335h0E23h0735hFFFEh14:35return to 0114h
28ret0235h3335h0E23h0735h0000h14:350000h from the stack; SP = 0000h
29INT 20h (PSP:0000h)0235h3335h0E23h0735h0000h14:35INT 20h ends the program

The last two lines show how the program ends. The RET returning from the procedure (step 27) pops 0114h from the stack and brings SP back to FFFEh. The main program's RET (step 28) loads the 0000h at the very top of the stack into IP, and SP = 0000h. 0000h is the start of the PSP, and the INT 20h that DOS placed there ends the program. 14:35 stays on the screen.

5.2.7INT 1Ah and the BIOS data area

5.2.7.1The tick counter and the real-time clock

On the PC two separate pieces of hardware keep time. The first is the 8253/8254 programmable timer. Channel 0 divides a 1,193,182 Hz clock by 65,536 and produces the IRQ 0 interrupt about 18.2 times per second. The BIOS routine attached to this interrupt (INT 08h) increments a counter in memory each time. This counter is called the tick counter; it holds the number of ticks since midnight. Because the counter is in memory, it is lost when the computer is switched off.

The second, found in the AT and later computers, is the real-time clock (RTC). The RTC is a battery-powered CMOS chip and keeps running while the computer is off. It keeps the hour, minute, second and date in its own registers as BCD; they are read through I/O ports 70h and 71h. At boot, DOS gets its time from the RTC and then advances it with the tick counter. INT 1Ah offers a BIOS interface to both clocks.

Table 5.2.27: INT 1Ah services.
AHFunctionReturn
00hread the tick counterCX:DX = number of ticks since midnight, AL = day-rollover flag
02hread the RTC timeCH = hour, CL = minute, DH = second (BCD), DL = daylight saving; CF = 1: error
04hread the RTC dateCH = century, CL = year, DH = month, DL = day (BCD); CF = 1: error
Definition 5.2.8

Packed BCD (packed binary-coded decimal) is a representation that puts two decimal digits in one byte: the high four bits (the high nibble) hold the tens digit and the low four bits the ones digit. The minute 35 is stored in packed BCD as 35h = 0011 0101b; in binary it is 23h = 0010 0011b.

The benefit of BCD is that the hexadecimal notation directly shows the decimal value: 35h reads as "thirty-five". No division is needed to write it on the screen; the two nibbles are separated and 30h is added to each. The high nibble is separated by shifting four bits to the right, the low nibble by masking with 0Fh. The 8086 has no constant shift count greater than 1; the shift count is given in CL.

Table 5.2.28: Converting packed BCD 35h to ASCII.
StepOperationResult
135h = 0011 0101bhigh nibble 3, low nibble 5
2shr dl, cl (CL = 4)0000 0011b = 03h
3and dl, 0Fh0000 0101b = 05h
4+30h'3' = 33h, '5' = 35h

INT 21h/2Ch gives the same minute in binary: CL = 23h. There AAM or division by 10 is needed. If the two methods are mixed up, a wrong number is written to the screen, but the error shows only for values of 10 and above, because between 0 and 9 BCD and binary are the same.

Example 5.2.7

The time is 14:23. The RTC gives the minute as CL = 23h (BCD). If this value is sent to the print2 procedure that uses AAM, AAM counts it as binary 35 and 35 is written on the screen. DOS, on the other hand, gives the minute as CL = 17h (binary 23). If this value is sent to a BCD routine, the nibbles are separated as 1 and 7 and 17 is written on the screen. The correct approach is to print the RTC value with SHR/AND and the DOS value with AAM.

Among the interrupts that emu8086 supports, only 00h (tick counter) is available for INT 1Ah. The 02h service works in a real DOS environment or in DOSBox; in emu8086 the time is read with INT 21h/2Ch.

5.2.7.2Code trace: printing the RTC time

The following program writes the RTC time as HH:MM:ss. The two procedures share an entry: colon first writes ':' and then, without any jump, falls through into putbcd. For the hour putbcd is called directly, for the minute and second colon is called.

org 100h
mov ah, 02h
int 1Ah          ; CH=hr CL=min DH=sec
jc  done         ; CF=1: clock error
mov bl, cl       ; save the minute
mov cl, 4        ; SHR count
mov bh, ch
call putbcd      ; "14"
mov bh, bl
call colon       ; ":35"
mov bh, dh
call colon       ; ":07"
done: ret
colon: mov dl, ':'
mov ah, 02h
int 21h
putbcd:          ; BH = packed BCD
mov dl, bh
shr dl, cl       ; high digit
add dl, 30h      ; ASCII digit
mov ah, 02h
int 21h
mov dl, bh
and dl, 0Fh      ; low digit
add dl, 30h
int 21h
ret

The program first looks at CF. If the RTC is not running or is being updated at that moment, the service returns CF = 1 and the program ends without printing. In the trace the time is 14:35:07 and CF = 0. On return CH = 14h, CL = 35h, DH = 07h; DL = 00h says that daylight saving is off.

The use of registers has been carefully planned. Since the shift count 4 will be written to CL, the minute is first copied to BL. The procedure expects the value in BH; the hour (CH), minute (BL) and second (DH) are put into BH in turn. DL is needed for writing characters; but since the second sits in DH, DL being clobbered is no problem. INT 21h/02h does not touch BX, CX or DH.

Table 5.2.29: Trace of the program that writes the RTC time as HH:MM:ss (time 14:35:07).
StepInstructionAXBXCXDXSPCFScreen (output)Explanation
1mov ah, 02h0200h0000h0000h0000hFFFEh0–AH = 02h: read the RTC time
2int 1Ah0200h0000h1435h0700hFFFEh0–CH = 14h, CL = 35h, DH = 07h (packed BCD); DL = 00h
3jc done0200h0000h1435h0700hFFFEh0–CF = 0: no jump
4mov bl, cl0200h0035h1435h0700hFFFEh0–the minute is saved in BL
5mov cl, 40200h0035h1404h0700hFFFEh0–CL = 4: the shift count
6mov bh, ch0200h1435h1404h0700hFFFEh0–BH = hour = 14h
7call putbcd0200h1435h1404h0700hFFFCh0–straight into putbcd
8mov dl, bh0200h1435h1404h0714hFFFCh0–DL = 14h = 0001 0100b
9shr dl, cl0200h1435h1404h0701hFFFCh0–4 bits right: 01h
10add dl, 30h0200h1435h1404h0731hFFFCh0–DL = 31h = '1'
12int 21h0231h1435h1404h0731hFFFCh011 on the screen
13mov dl, bh0231h1435h1404h0714hFFFCh01DL = 14h again
14and dl, 0Fh0231h1435h1404h0704hFFFCh01top 4 bits cleared: 04h
15add dl, 30h0231h1435h1404h0734hFFFCh01DL = 34h = '4'
16int 21h0234h1435h1404h0734hFFFCh0144 on the screen
17ret0234h1435h1404h0734hFFFEh014return
18mov bh, bl0234h3535h1404h0734hFFFEh014BH = minute = 35h
19call colon0234h3535h1404h0734hFFFCh014entry at colon
22int 21h023Ah3535h1404h073AhFFFCh014:: on the screen
23mov dl, bh023Ah3535h1404h0735hFFFCh014:falls through into putbcd
27int 21h0233h3535h1404h0733hFFFCh014:33 on the screen
31int 21h0235h3535h1404h0735hFFFCh014:355 on the screen
32ret0235h3535h1404h0735hFFFEh014:35return
33mov bh, dh0235h0735h1404h0735hFFFEh014:35BH = second = 07h
37int 21h023Ah0735h1404h073AhFFFCh014:35:: on the screen
42int 21h0230h0735h1404h0730hFFFCh014:35:00 on the screen
46int 21h0237h0735h1404h0737hFFFCh014:35:077 on the screen
47ret0237h0735h1404h0737hFFFEh014:35:07return
48ret0237h0735h1404h0737h0000h014:35:07program ends: SP = 0000h

For the hour putbcd writes twice. DL = 14h = 0001 0100b; SHR DL, CL shifts four bits right and DL = 01h. With 30h added, '1' is written. Then DL is loaded with 14h again, AND DL, 0Fh clears the top four bits and DL = 04h; '4' goes to the screen. Since AH is still 02h after the first call, it is not reloaded for the second INT 21h. For the minute, the colon entry first writes ':'; then the instructions fall through into the putbcd label. A label is not an instruction, only an address. In the final state the screen shows 14:35:07.

Common mistake

Writing MOV CL, 4 without saving the minute. The 35h in CL is lost and 04h is printed in place of the minute. Another mistake is to write SHR DL, 4 for the 8086. This form exists on the 80186 and later processors; on the 8086 the shift count is either 1 or CL.

5.2.7.3The BIOS data area

The BIOS keeps the state of the hardware at a fixed place in memory: in segment 0040h, physically in the area starting at 00400h. This area is called the BIOS data area. INT 16h reads the keyboard buffer, INT 1Ah the tick counter, and INT 10h the video mode and cursor positions from here. A program can read the same bytes directly. Table 5.2.30 lists frequently used locations.

Table 5.2.30: Selected locations in the BIOS data area.
AddressSizeContents
0040:0010wordequipment list (the value returned by INT 11h)
0040:0013wordbase memory, KB (INT 12h)
0040:0017bytekeyboard flags: bit 0 right Shift, 1 left Shift, 2 Ctrl, 3 Alt, 4 Scroll Lock, 5 Num Lock, 6 Caps Lock, 7 Insert
0040:001Awordbuffer head: the offset of the next key to be read
0040:001Cwordbuffer tail: the offset of the next free place (head = tail → buffer empty)
0040:001E–003D32 byteskeyboard buffer: 16 words (ASCII + scan code), circular; at most 15 keys
0040:0049bytecurrent video mode (03h, 13h …)
0040:004Awordnumber of columns on the screen (80 in mode 03h)
0040:00508 wordscursor positions of the 8 pages (low byte column, high byte row)
0040:006Cdouble wordtick counter: number of ≈ 18.2 Hz interrupts since midnight
0040:0070bytemidnight-passed flag (INT 1Ah/00h returns it in AL and clears it)

The physical address is found by multiplying the segment value by 16 and adding the offset: 0040:006C = 00400h + 006Ch = 0046Ch. The same byte can also be reached with the address 0000:046Ch; the two segment:offset pairs point to the same physical address.

The keyboard buffer is a circular queue. INT 09h writes the new key at the "tail" position and advances the tail by two bytes; INT 16h reads from the "head" position and advances the head. When one of the positions reaches the end of the area (003Eh), it wraps back to 001Eh. If head and tail are equal, the buffer is empty. That is why the 16-word area holds at most 15 keys: if a 16th key were written, the tail would equal the head and a full buffer would be taken for an empty one.

Example 5.2.8

0024h is read at 0040:001Ah and 0028h at 0040:001Ch. Since each key is one word, the number of waiting keys is (0028h − 0024h) ÷ 2 = 2. The ASCII code of the next key is at 0040:0024h and its scan code at 0040:0025h. The physical address of 0040:001Ah is 0041Ah.

5.2.7.4Waiting with the tick counter

The tick counter is a ready-made clock for short waits. The program reads the starting value and then waits in a loop until the counter has advanced by the desired amount. The code below also tests Caps Lock in the keyboard flags and checks whether there is a key waiting in the buffer.

; wait about 1 second
mov ax, 0040h
mov es, ax
mov bx, es:[006Ch]   ; starting tick
wait1:
mov ax, es:[006Ch]   ; current tick
sub ax, bx           ; ticks elapsed
cmp ax, 18           ; 18 ticks ≈ 0.99 s
jb wait1
; Caps Lock on? Any key waiting?
test byte ptr es:[0017h], 40h
jnz caps_on          ; bit 6 = 1
mov ax, es:[001Ah]   ; buffer head
cmp ax, es:[001Ch]   ; buffer tail
je buf_empty

The duration of a tick is computed from the timer's division ratio. Table 5.2.31 gives the values.

Table 5.2.31: Time values of the tick counter.
QuantityCalculationValue
Tick rate1,193,182 Hz ÷ 65,53618.2065 Hz
One tick65.536 ÷ 1.193.182 s≈ 54.9 ms
18 ticks18 × 54.925 ms≈ 0,989 s
5 seconds5 × 18,2065≈ 91 ticks
One daythe value at which the counter resets1800B0h = 1,573,040 ticks

Because the wait is measured in ticks, the resolution is about 55 ms; shorter times cannot be measured this way. The code reads only the low word of the counter. Since a difference is taken, the result is correct even if the low word wraps from FFFFh to 0000h: a 16-bit subtraction gives the correct difference modulo 216 (mod 65,536). Only the reset at midnight spoils the calculation, because the counter jumps from 1800B0h to 0.

The Caps Lock check is done with TEST. The mask 40h = 0100 0000b selects bit 6; if the bit is 1 the result is not zero, ZF = 0 and JNZ jumps. TEST only reads the flags; it does not change the byte in the BIOS data area. The buffer check compares head and tail; if they are equal there is no waiting key. emu8086 does not update the whole BIOS data area as a real PC does; the tick counter and keyboard buffer examples work fully in DOSBox.

Common mistake

Adding the wait time to the start value and looking for the counter to equal the resulting end value: cmp ax, target / jne wait1. The counter can pass the target at a moment when the loop does not read it in that very iteration, and the loop then runs until the next wraparound. It is safe to take a difference and ask "has at least this much passed?" with JB.

5.2.8Program termination

5.2.8.1Three ways and the exit code

When a program has finished its work, it must give control back to DOS. The processor knows nothing of an "end of the program"; it always executes the byte IP points to as an instruction. If the termination instruction is forgotten, the processor runs the bytes after the program, often the program's data, as instructions. The result is unpredictable: garbage may be printed on the screen, the system may lock up. DOS offers three ways to end a program (Table 5.2.32).

Table 5.2.32: Three ways to terminate a program.
MethodHow it worksWhere
retIn a COM program the top of the stack holds 0000h; RET returns to PSP:0000h, where int 20h (CD 20) sits.COM only, if the stack is balanced
int 20hDOS terminates the program; CS must point to the PSP segment.COM
mov ax, 4C00h
int 21h
Terminates with the exit code in AL and closes open files.COM and EXE · recommended
Definition 5.2.9

The PSP (Program Segment Prefix) is the 256-byte area DOS places in front of every program. The command line, the address of the environment variables and return information are kept here. Its first two bytes are CD 20, that is the INT 20h instruction. Because COM programs are loaded right after the PSP, the code begins at ORG 100h.

Why RET ends a COM program can be understood from the stack. When DOS starts a COM program, it sets SP to FFFEh and puts the word 0000h there. If the program has left the stack balanced, that is, every PUSH has been followed by a POP and every CALL by a RET, the last RET loads this 0000h into IP. CS is still the program's segment and CS:0000h is the start of the PSP. There INT 20h runs and the program ends. If an extra word is left on the stack, RET takes that word for an address and jumps to some random place.

The recommended way is INT 21h/4Ch. It works in both COM and EXE programs, does not depend on the value of CS, and gives DOS an exit code. The exit code is in AL: 0 means success, nonzero values mean an error. A batch file (.BAT) can test this code with IF ERRORLEVEL 1 and take different paths.

5.2.8.2COM and EXE templates

emu8086 offers two templates for a new program. In the COM template code, data and stack are in a single 64 KB segment. In the EXE template each sits in a separate segment.

org 100h
    mov dx, offset msg
    mov ah, 09h
    int 21h
    ret            ; or int 20h
msg db 'Welcome$'

In a COM program CS = DS = ES = SS; the program does not set the segment registers. Code, data and stack together can be at most 64 KB. The file is machine code only, with no header at the start. DOS copies the file right behind the PSP, at offset 100h, and starts execution from there.

.model small
.stack 100h
.data
msg db 'Welcome$'
.code
start:
mov ax, @data
mov ds, ax       ; set DS!
mov dx, offset msg
mov ah, 09h
int 21h
mov ax, 4C00h
int 21h
end start

An EXE file has a header at its start. The header holds which segments the program consists of and the places that must be adjusted according to the load address (relocation information). The entry point is given with end start and the program can be larger than 64 KB. At start DOS sets CS:IP to the entry point and SS:SP to the stack segment. DS and ES point to the PSP. Before accessing the data segment, the program must set DS itself: mov ax, @data and mov ds, ax. @data is the segment value of the data segment; DOS fills in this value at load time.

Table 5.2.33: Trace of the EXE template (segment values according to the emu8086 layout).
StepInstructionAXDSDXScreen (output)Explanation
1mov ax, @data0720h0700h0000h–@data = data segment 0720h; DS still points to the PSP
2mov ds, ax0720h0720h0000h–DS = 0720h: the data segment
3mov dx, offset msg0720h0720h0000h–msg is at the start of the data segment
4mov ah, 09h0920h0720h0000h–AH = 09h
5int 21h0924h0720h0000hWelcomefrom 0720:0000 up to the '$'
6mov ax, 4C00h4C00h0720h0000hWelcomeAH = 4Ch, AL = 00h
7int 21h4C00h0720h0000hWelcomereturn to DOS with exit code 0
DS0720hAX0720hDX0000h0700h PSP (256 bytes)0710h stack (.stack 100h)0720h data: 'Welcome$'DS0721h codeCSscreen▌
Figure 5.2.14: The segments after MOV DS, AX: PSP 0700h, stack 0710h, data 0720h (DS), code 0721h (CS). The segment values are emu8086's layout; on real DOS the numbers may differ, but the order and the need to set DS are the same.

At the start DS = ES = 0700h, that is, the PSP. The stack segment is 0710h: since the 256 bytes of the PSP are 16 paragraphs, 0700h + 10h. .stack 100h reserves a 256-byte stack, which is 10h paragraphs; the data segment therefore starts at 0720h. The 8 bytes of data fit in one paragraph and the code starts at 0721h. MOV AX, @data loads 0720h into AX; MOV DS, AX turns DS into the data segment. Because an immediate value cannot be written into a segment register, two steps are needed. msg is at the start of the data segment: OFFSET msg = 0000h. 09h writes Welcome starting at DS:DX = 0720:0000h. The last two lines return to DOS with exit code 0.

RET cannot be used in an EXE program. DOS does not put 0000h on an EXE's stack; SS:SP points to the program's own stack segment. RET jumps to whatever it finds there. If the MOV DS, AX line is forgotten, DX holds the right offset but the segment is wrong: DS:DX points to the start of the PSP and the bytes of the PSP, that is garbage, are printed on the screen.

5.2.9Application: printing the result in binary

5.2.9.1The program

The program in this part combines many services with a small calculation. First 5 + 10 − 1 = 14 is computed and the result is written to BL. Then the eight bits of BL, starting from the most significant bit (MSB), are printed on the screen one by one as the character '0' or '1'. At the end the binary suffix 'b' is written and a key press is awaited. The expected output is 00001110b.

org 100h
mov al, 5        ; 00000101b
mov bl, 10       ; 0Ah = 00001010b
; 5 + 10 = 15 = 0Fh = 00001111b
add bl, al
; 15 - 1 = 14 = 0Eh = 00001110b
sub bl, 1
mov cx, 8        ; print result in binary
print:
mov ah, 2        ; print function
mov dl, '0'
test bl, 10000000b  ; test top bit
jz zero
mov dl, '1'
zero:
int 21h
shl bl, 1
loop print
; print the binary suffix b
mov dl, 'b'
int 21h
; wait for a key press
mov ah, 0
int 16h
ret

The number does not need to be "made binary" in memory or in a register; it is binary already. Printing means converting each bit to an ASCII character: 30h for a 0 bit, 31h for a 1 bit. On each iteration the loop looks at bit 7, writes the character, and shifts the number one bit left. The next bit thus takes the place of bit 7. After eight iterations all the bits have been written from left to right.

5.2.9.2Reading bits with TEST and SHL

TEST BL, 10000000b ANDs BL with the mask bit by bit but writes the result nowhere; it only sets the flags. The mask has a single 1 bit, at bit 7. If bit 7 of BL is 0 the AND result is 0 and ZF = 1 is set. If bit 7 = 1 the result is 80h and ZF = 0. JZ jumps when ZF = 1. TEST also always clears CF and OF.

BL0706050413121100mask10000000AND → 00000000ZF = 1 (bit 7 = 0)
Figure 5.2.15: TEST BL, 10000000b: BL = 00001110b is ANDed with the mask and the result is 00000000b; ZF = 1 (bit 7 = 0). BL does not change.

SHL BL, 1 shifts all the bits one place left. The bit that leaves from bit 7 goes to CF and a 0 enters at bit 0. The next bit is now in the place of bit 7. Because TEST does not store its result, it does not spoil BL; the only instruction that changes it, deliberately, is SHL.

before0706050413121100after00011100CF0bit 7 → CF0 enters from the right
Figure 5.2.16: SHL BL, 1: 00001110b → 00011100b; the bit that leaves, bit 7 (0), goes to CF and a 0 enters from the right.

The same job can also be done by looking at CF after SHL: first SHL BL, 1, then JC tests whether the bit that left was 1. In this order the shift must be done before printing, because the value of the bit is now in CF, not in BL. There is also a reason for redoing MOV AH, 2 on every iteration: INT 21h/02h does not spoil AH, but if another service is added to the loop later, AH will already be protected.

5.2.9.3Code trace

How the flags change in the calculation part is seen in Table 5.2.34. The MOV instructions do not touch the flags. ADD BL, AL produces 0Ah + 05h = 0Fh and there is no carry (CF = 0). The result has four 1 bits; because the parity is even, PF = 1. SUB BL, 1 produces 0Eh = 00001110b; three 1 bits make PF 0, and there is no borrow (CF = 0).

Table 5.2.34: Trace of the calculation part (flags after each instruction).
StepInstructionAHDLBLCXZFCFPFScreen (output)Explanation
1mov al, 500h00h00h0000h000–AL = 05h; MOV does not change the flags
2mov bl, 1000h00h0Ah0000h000–BL = 0Ah
3add bl, al00h00h0Fh0000h001–0Ah + 05h = 0Fh; four 1 bits: PF = 1
4sub bl, 100h00h0Eh0000h000–0Fh − 1 = 0Eh; three 1 bits: PF = 0
5mov cx, 800h00h0Eh0008h000–eight iterations for eight bits

The eight iterations of the loop follow the same pattern. Table 5.2.35 gives two iterations step by step: the first, where bit 7 is 0, and the fifth, where it is 1. In the first iteration TEST makes ZF = 1, JZ jumps and the '0' in DL is written. In the fifth iteration BL = E0h; TEST makes ZF = 0, JZ does not jump, MOV DL, '1' runs and '1' is written. In both iterations SHL throws the bit that leaves into CF, and LOOP decreases CX by one.

Table 5.2.35: Iterations 1 and 5 of the loop step by step (in iteration 5, bit 7 = 1).
StepInstructionAHDLBLCXZFCFPFScreen (output)Explanation
6mov ah, 202h00h0Eh0008h000–iteration 1: AH = 2
7mov dl, '0'02h30h0Eh0008h000–default '0'
8test bl, 10000000b02h30h0Eh0008h101–0Eh AND 80h = 0: ZF = 1
9jz zero02h30h0Eh0008h101–ZF = 1: jump to zero
10int 21h02h30h0Eh0008h10100 on the screen
11shl bl, 102h30h1Ch0008h0000BL = 1Ch; the bit that left is 0
12loop print02h30h1Ch0007h0000CX = 7 ≠ 0: to print
34mov ah, 202h30hE0h0004h0000000iteration 5: AH = 2
35mov dl, '0'02h30hE0h0004h0000000default '0'
36test bl, 10000000b02h30hE0h0004h0000000E0h AND 80h = 80h: ZF = 0
37jz zero02h30hE0h0004h0000000no jump
38mov dl, '1'02h31hE0h0004h0000000DL = '1'
39int 21h02h31hE0h0004h000000011 on the screen
40shl bl, 102h31hC0h0004h01100001BL = C0h; the bit that left, CF = 1
41loop print02h31hC0h0003h01100001CX = 3 ≠ 0: to print

Table 5.2.36 is a summary of the eight iterations. BL shifts one place left on each iteration: 0Eh, 1Ch, 38h, 70h, E0h, C0h, 80h, 00h. The bit 7 column gives the order of the characters written: 0, 0, 0, 0, 1, 1, 1, 0. This is the binary notation of 0Eh. After the eighth iteration CX = 0 and LOOP does not jump.

Table 5.2.36: Summary of the eight iterations (each row is the state after that iteration's LOOP instruction).
IterationBL (before TEST)Bit 7WrittenBL (after SHL)CFCXScreen
10Eh = 00001110001Ch00007h0
21Ch = 000111000038h00006h00
338h = 001110000070h00005h000
470h = 0111000000E0h00004h0000
5E0h = 1110000011C0h10003h00001
6C0h = 110000001180h10002h000011
780h = 100000001100h10001h0000111
800h = 000000000000h00000h00001110

After the loop DL = 'b' is set, and because AH is still 2, INT 21h writes 'b' directly. MOV AH, 0 and INT 16h wait for a key; in the trace, when Enter is pressed, AH = 1Ch (scan code), AL = 0Dh are returned. The last RET ends the program. The final state of the screen is as follows:

00001110b_
Example 5.2.9

Let the same loop run with BL = B5h. B5h = 1011 0101b. In the iterations bit 7 is, in turn, 1, 0, 1, 1, 0, 1, 0, 1 and 10110101b is written on the screen. The bits that SHL throws into CF in the iterations follow the same order, because the bit that leaves is, on each iteration, the bit TEST looked at.

The lessons from the program are brief. Because LOOP decreases CX, CX is not used for anything else inside the loop. INT 21h/02h changes AL (AL = DL); if there is a value kept in AL it must be protected first. TEST sets the flags but does not change the operand; so the same register can be tested one after another with many masks.

5.2.9.4A mini menu

The last program is the skeleton of a user interface: it shows a menu, reads a key, and acts according to the key. The '1' key says hello, 'q' ends the program, and any other key shows the menu again.

org 100h
show:
mov dx, offset menu
mov ah, 09h
int 21h
mov ah, 01h      ; read the choice
int 21h
cmp al, 'q'
je quit
cmp al, '1'
jne show
mov dx, offset greet
mov ah, 09h
int 21h
jmp show
quit:
mov ax, 4C00h    ; exit code 0
int 21h
menu  db 0Dh, 0Ah, '1:Hello q:Leave $'
greet db 0Dh, 0Ah, 'Hello!$'

The user presses 1 and then q. Table 5.2.37 gives the trace.

Table 5.2.37: Trace of the mini menu program (keys pressed: 1, q).
StepInstructionAXDXZFScreen (output)Explanation
1mov dx, offset menu0000h0121h0–DX → the menu text
2mov ah, 09h0900h0121h0–AH = 09h
3int 21h0924h0121h0↵1:Hello q:Leave CR LF and the menu are written
4mov ah, 01h0124h0121h0↵1:Hello q:Leave AH = 01h: read and echo
5int 21h0131h0121h0↵1:Hello q:Leave 11: AL = 31h
6cmp al, 'q'0131h0121h0↵1:Hello q:Leave 131h − 71h ≠ 0: ZF = 0
7je quit0131h0121h0↵1:Hello q:Leave 1no jump
8cmp al, '1'0131h0121h1↵1:Hello q:Leave 131h − 31h = 0: ZF = 1
9jne show0131h0121h1↵1:Hello q:Leave 1equal: no jump
10mov dx, offset greet0131h0134h1↵1:Hello q:Leave 1DX → greet
12int 21h0924h0134h1↵1:Hello q:Leave 1↵Hello!Hello! on a new line
13jmp show0924h0134h1↵1:Hello q:Leave 1↵Hello!back to the menu
16int 21h0924h0121h1↵1:Hello q:Leave 1↵Hello!↵1:Hello q:Leave the menu is written again
18int 21h0171h0121h1↵1:Hello q:Leave 1↵Hello!↵1:Hello q:Leave qq: AL = 71h
19cmp al, 'q'0171h0121h1↵1:Hello q:Leave 1↵Hello!↵1:Hello q:Leave qequal: ZF = 1
20je quit0171h0121h1↵1:Hello q:Leave 1↵Hello!↵1:Hello q:Leave qjump to quit
21mov ax, 4C00h4C00h0121h1↵1:Hello q:Leave 1↵Hello!↵1:Hello q:Leave qAH = 4Ch, AL = 00h
22int 21h4C00h0121h1↵1:Hello q:Leave 1↵Hello!↵1:Hello q:Leave qreturn to DOS with exit code 0

Because the menu text begins with CR LF, it is written on a new line at each display. AH = 01h reads the key and echoes it; the 1 the user pressed appears right next to the menu. The first comparison is between 31h and 71h ('q'); they are not equal, ZF = 0 and JE does not jump. The second comparison is made with '1'; they are equal, ZF = 1 and JNE does not jump. greet is written and JMP returns to the menu. In the second iteration q is read, CMP AL, 'q' makes ZF = 1 and JE jumps to quit. MOV AX, 4C00h sets AH = 4Ch and AL = 00h in a single instruction; the program ends with exit code 0. The final state of the screen is this:


1:Hello q:Leave 1
Hello!
1:Hello q:Leave q

The data sits after the last instruction. Because INT 21h/4Ch does not return, the processor never reaches the bytes of menu. If the termination lines were deleted, the processor would try to decode the bytes 0Dh, 0Ah, '1' … as instructions.

5.2.9.5Common mistakes

Most of the errors in programs that call services fall into a few patterns. Table 5.2.38 collects them with their causes and fixes.

Table 5.2.38: Frequent mistakes with interrupt services.
MistakeResultFix
'$' forgottenINT 21h/09h writes memory until it finds '$'; garbage fills the screen'$' at the end of the string
DS not set (EXE)DX is right but the segment is wrong; the PSP is printedmov ax, @data · mov ds, ax
AL clobbered02h and 09h change AL; the character read is lostsave the value in another register
cursor after 09hINT 10h/09h does not advance the cursor; the next text lands on topmove the cursor with 02h
DS:DX with 13hthe BIOS string service expects the address in ES:BPlea bp, msg; DX is the position
0Ah buffercapacity not written, or the text read from buffer+0byte 0 = capacity; text at buffer+2
LF onlythe cursor goes down a line but not to the start of the lineCR + LF (0Dh, 0Ah)
No terminationthe data is executed as instructionsRET (COM) or INT 21h/4Ch
Common mistake

To rewrite a key that was read on a new line, this order is used: read with AH = 01h, write CR and LF with AH = 02h, then write the key with MOV DL, AL. When the user presses k, only the echoed k appears on the screen and the cursor goes down two lines. After the last 02h call AL = 0Ah; MOV DL, AL takes the LF, not the key. The key that was read is saved at once with MOV BL, AL, and then MOV DL, BL is written.

5.2.10Exercises and solutions

The exercises in the slides are given below with their solutions. For the exercises that ask for a program, the code is followed by a short explanation of the solution. The solutions are not the only way; programs that do the same job with other services are also correct.

Exercise 1. How is a program written with INT 10h/13h that writes "8086" in white on a blue background exactly in the middle of the screen at (12, 38)?

org 100h
mov ax, 1301h      ; AH=13h, AL=01h
mov bx, 001Fh      ; BH=0, BL=1Fh
mov cx, 4          ; 4 characters
mov dx, 0C26h      ; row 12, column 38
lea bp, text       ; ES:BP → string
int 10h
ret
text db '8086'

The four characters are written to columns 38–41; since the middle of the 80-column screen is 40, the text is centered. DX = 0C26h means DH = 0Ch = 12 and DL = 26h = 38. BL = 1Fh is white text on a blue background. In a COM program ES = DS, so ES is not set separately. The place of the first cell in video memory is (12 × 80 + 38) × 2 = 07CCh.

Exercise 2. How is a program written that reads two digits (01h) from the user and prints their sum as a single digit (sum ≤ 9)?

org 100h
mov ah, 01h
int 21h            ; first digit
sub al, 30h
mov bl, al
mov ah, 01h
int 21h            ; second digit
sub al, 30h
add bl, al         ; BL = sum
mov ah, 02h
mov dl, 0Dh
int 21h
mov dl, 0Ah
int 21h
mov dl, bl
add dl, 30h        ; ASCII digit
int 21h
ret

The numeric value is found by subtracting 30h from each digit. The first number is saved in BL, because the second read changes AL. The sum forms in BL and is written after CR LF with 30h added. When the user presses 3 and 5, 35 appears on the screen and 8 on the line below.

Exercise 3. How is a program written that prints, in hexadecimal, the scan codes of the keys pressed until Esc is pressed?

org 100h
read:
mov ah, 0
int 16h            ; AH = scan, AL = ASCII
cmp al, 1Bh        ; Esc?
je done
lea bx, hex        ; XLAT table
mov dh, ah         ; save the scan code
mov al, dh
mov cl, 4
shr al, cl         ; high digit
xlat
mov dl, al
mov ah, 02h
int 21h
mov al, dh
and al, 0Fh        ; low digit
xlat
mov dl, al
int 21h
mov dl, ' '
int 21h
jmp read
done: ret
hex db '0123456789ABCDEF'

The scan code arrives in AH and is saved in DH, because AL and AH will change with the XLAT and 02h calls. XLAT performs AL ← [BX + AL]: it converts a number from 0 to 15 into the character in the table. The high digit is separated by shifting four bits right, the low digit by masking with 0Fh. When the a and 1 keys are pressed, 1E 02 appears on the screen; Esc ends the program.

Exercise 4. How is a program written that prints the text read with 0Ah in reverse?

org 100h
mov dx, offset buffer
mov ah, 0Ah
int 21h            ; read a line
mov ah, 02h
mov dl, 0Ah        ; next line (Enter echoed a CR)
int 21h
mov cl, [buffer+1] ; count read
mov ch, 0
jcxz done
mov si, offset buffer+1
add si, cx         ; last character
std                ; backwards
rev:
lodsb
mov dl, al
int 21h
loop rev
cld
done: ret
buffer db 20, ?, 20 dup(?)

The text starts at buffer+2 and its length is in [buffer+1]. The last character is at address buffer + 2 + count − 1 = buffer + 1 + count; SI is set there. STD sets the direction flag and LODSB does AL ← [SI] on each iteration and decreases SI by one. Because CX = count, LOOP writes each character once. For an empty line (count 0) JCXZ never enters the loop; otherwise LOOP would take CX from 0 to FFFFh and run 65,536 iterations. At the end of the program CLD returns the direction flag to its default. When Micro is typed, orciM appears on the next line.

Exercise 5. How is the date printed in the format DD.MM.YYYY? What method is used for the year?

org 100h
mov ah, 2Ah
int 21h            ; CX=year DH=month DL=day
mov bx, cx         ; save the year
mov al, dl
call print2        ; DD
mov dl, '.'
int 21h
mov al, dh
call print2        ; MM
mov dl, '.'
int 21h
mov ax, bx         ; year
mov cx, 0          ; digit counter
mov si, 10
div10:
xor dx, dx
div si             ; DX:AX / 10
push dx            ; remainder = digit
inc cx
test ax, ax
jnz div10
mov ah, 02h
emit:
pop dx
add dl, 30h
int 21h
loop emit
ret
print2:            ; AL (0-99) → 2 digits, DH preserved
push dx
aam
add ax, 3030h
push ax
mov dl, ah
mov ah, 02h
int 21h
pop ax
mov dl, al
mov ah, 02h
int 21h
pop dx
ret

Since the day and month are smaller than 99, AAM is enough; the print2 procedure preserves the month in DH on the stack. The year is a 16-bit number and cannot be split with AAM. The year is divided by 10 repeatedly: DIV SI divides DX:AX by 10, writing the quotient to AX and the remainder to DX. The remainders come out in the order ones, tens, hundreds, thousands; the order of writing is the reverse. So the remainders are pushed on the stack and then popped and written. DX is zeroed before every division, because DIV takes the dividend as DX:AX. For January 7, 2026, 07.01.2026 is written on the screen.

Exercise 6. How is the '$' character printed with mov ah, 09h / int 21h?

It cannot be printed; 09h counts the first '$' as the end of the string and does not write it. For '$' the 02h service is used: mov ah, 02h, mov dl, '$' (24h), int 21h. INT 10h/0Eh with AL = 24h does the same job.

Exercise 7. What is the offset, within segment A000h, of pixel (160, 100) in mode 13h?

100 × 320 + 160 = 32,160 = 7DA0h. The physical address is A7DA0h.

Exercise 8. INT 1Ah/02h returned DH = 59h. What is written on the screen? With what value would the same second arrive from INT 21h/2Ch?

59h is packed BCD: high nibble 5, low nibble 9; 59 is written on the screen. INT 21h/2Ch gives the second in binary: 59 = 3Bh, that is DH = 3Bh.

Exercise 9. How many ticks must be waited to wait about 5 seconds with the tick counter at 0040:006C?

5 × 18.2065 ≈ 91 ticks. At 54.9 ms per tick, 91 ticks is 4.998 seconds.

5.2.11Summary

  • The BIOS is a set of ROM routines that drive the hardware directly; DOS, on top of it, offers file, string, clock and program services. A program reaches both with INT n, without knowing the address of the service.
  • The service-call pattern: AH ← service number, parameters in the other registers, INT n, result in registers or flags. Services change some registers: INT 21h/02h makes AL = DL, 09h makes AL = 24h.
  • A new line takes CR LF (0Dh, 0Ah). Digit = code − 30h; uppercase and lowercase letters differ in bit 5.
  • INT 10h: 00h selects the mode and clears the screen; 02h/03h set and read the cursor. 09h writes in color but does not advance the cursor; 0Eh writes teletype and advances the cursor. 13h writes the string at ES:BP of length CX; 06h scrolls or clears a window.
  • Attribute = background × 16 + foreground; bit 7 is blink. 07h is the default, 1Fh is white on blue, 4Eh is yellow on red.
  • In mode 03h the video memory is at B800:0000h; the cell is at address (row × 80 + column) × 2, with the character in the even byte and the attribute in the odd byte. In mode 13h, from A000:0000h there is one byte per pixel and the address is y × 320 + x.
  • INT 16h/00h waits for a key and gives the scan code in AH and ASCII in AL; for extended keys AL = 00h. 01h polls without waiting: ZF = 1 means no key.
  • INT 21h: 01h reads and echoes, 02h writes DL, 09h writes a '$'-terminated string, 0Ah reads a buffered line. DOS output can be redirected; BIOS output cannot.
  • The 0Ah buffer: byte 0 capacity, byte 1 number read, the text starts at byte 2 and ends with 0Dh.
  • INT 21h/2Ah and 2Ch give the date and time in binary (printed with AAM); INT 1Ah/02h gives the RTC time in packed BCD (printed with SHR and AND).
  • The BIOS data area is in segment 0040h: keyboard flags at 0017h, buffer head and tail at 001Ah and 001Ch, tick counter at 006Ch. The tick rate is 18.2065 Hz, one tick ≈ 54.9 ms.
  • A program ends with RET (only a COM program with a balanced stack), INT 20h (COM) or the recommended INT 21h/4Ch; AL is the exit code. An EXE program sets DS itself with @data.

5.2.12Key terms

  • BIOS (Basic Input/Output System)
  • software interrupt
  • interrupt vector
  • ASCII ASCII
  • video mode
  • cursor
  • attribute byte
  • pixel
  • little-endian
  • scan code
  • keyboard buffer
  • polling
  • packed / unpacked BCD
  • nibble
  • real-time clock (RTC)
  • program segment prefix (PSP)
  • program termination
  • emulator

5.2.13Test Yourself

  1. In mode 03h, with the cursor at (24, 0), INT 10h is called with AH = 09h, AL = '-', BL = 1Eh, CX = 80. What appears on the screen, and where does the cursor stay?

    Answer

    A yellow '-' on a blue background is written into all 80 cells of the last row. 09h does not advance the cursor and does not scroll the screen; the cursor stays at (24, 0). If the same row were written 80 times with 0Eh, after the last character the cursor would try to move to the next line and the screen would scroll up one line.

  2. What is the attribute byte of blinking white text on a red background?

    Answer

    Bit 7 = 1 (blink), background 100b (red), foreground 1111b (white): 1100 1111b = CFh.

  3. In mode 03h, at what offset is the character byte of the first cell (24, 0) of the last row? What is its physical address?

    Answer

    (24 × 80 + 0) × 2 = 3840 = 0F00h. The character is at B800:0F00h and the attribute at B800:0F01h. The physical address is B8000h + 0F00h = B8F00h.

  4. While reading into a buffer defined as buffer db 4, ?, 4 dup(?) with INT 21h/0Ah, the user types abcdef and presses Enter. What are the first six bytes of the buffer?

    Answer

    Because the capacity is 4 including Enter, at most 3 characters are accepted; the bell rings at d, e and f. The buffer becomes 04 03 61 62 63 0D: the capacity, the count 3, 'a', 'b', 'c' and Enter.

  5. What is AL after the instructions mov ah, 02h, mov dl, 'Z', int 21h?

    Answer

    INT 21h/02h puts DL into AL on return: AL = 5Ah ('Z'). If a value had been kept in AL before, it is lost.

  6. The time is 23:00. A program that reads the time from DOS (INT 21h/2Ch) sends CH to the routine that prints BCD (SHR/AND). What appears on the screen? What would appear if CH read from the RTC were sent to the routine that uses AAM?

    Answer

    DOS gives binary: CH = 23 = 17h. The BCD routine separates the nibbles as 1 and 7 and writes 17. The RTC gives CH = 23h; AAM counts this as binary 35 (23h = 35) and 35 is written. In both cases the correct value is 23.

  7. How many ticks must be waited to wait about 3 seconds with the tick counter? Can a 10 ms wait be measured this way?

    Answer

    3 × 18.2065 ≈ 54.6; about 55 ticks. 10 ms cannot be measured: one tick is about 54.9 ms and the counter cannot tell apart intervals shorter than that.

  8. In mode 13h, what is the offset of pixel (200, 150)? What are the offsets of the pixels one to the right and one below?

    Answer

    150 × 320 + 200 = 48,200 = BC48h. The one to the right, (201, 150), is at BC49h; the one below, (200, 151), is at BC48h + 140h = BD88h.

  9. In the BIOS data area the buffer head is read as 003Ch and the buffer tail as 0020h. How many keys are waiting?

    Answer

    Because the buffer is circular, the tail may have fallen behind the head. From the head to the end of the area (003Ch–003Dh) there is one word, and from the start of the area to the tail (001Eh–001Fh) one word: 2 keys. The general formula is (tail − head + 32) mod 32, divided by 2: (20h − 3Ch + 20h) = 4 bytes.

  10. An EXE program ends with RET instead of MOV AX, 4C00h · INT 21h. What happens?

    Answer

    There is no 0000h word placed by DOS on the EXE's stack and CS does not point to the PSP. RET loads whatever it finds at the top of the stack into IP and jumps to a random address in the code segment. The program may lock up. An EXE program is ended with INT 21h/4Ch.

5.2.14Further reading

  • Ralf Brown, Ralf Brown's Interrupt List: a reference list that describes all the services of INT 10h, 16h, 1Ah and 21h at register level, with BIOS version differences.
  • IBM, Personal Computer AT Technical Reference, 1984: the BIOS source listing; the original definition of the BIOS data area and of the keyboard and timer interrupts.
  • Peter Abel, IBM PC Assembly Language and Programming, 5th ed.: covers the screen, keyboard and DOS services with many example programs.
  • Barry B. Brey, The Intel Microprocessors, 8th ed.: treats BIOS and DOS calls together with the 8086 hardware and interrupt structure.

5.2.15References

  1. R. Brown, Ralf Brown's Interrupt List (detailed reference for INT 10h, 16h, 21h).
  2. IBM, Personal Computer AT Technical Reference, BIOS section, 1984.
  3. P. Abel, IBM PC Assembly Language and Programming, 5th ed., Prentice Hall, 2001.
  4. B. B. Brey, The Intel Microprocessors, 8th ed., Pearson, 2009.
  5. emu8086 help documents: supported interrupt functions.
  6. Ş. Ç. Öztürk, O. Ergin, Intel 8086 ile Mikroişlemci Programlamaya Giriş (in Turkish), 2009.
  7. Intel, 8086 16-Bit HMOS Microprocessor data sheet (instruction timings).