NOTES IN ASSEMBLY LANGUAGE ENG. MOHAMED ZAKI, M.SC SPRING 2004 D:\612925830.doc 1 ASSEMBLY LANGUAGES TOC NUMBERING SYSTEMS __________________________________________ 5 Representation of numbers ______________________________________________ Decimal_____________________________________________________________ Binary ______________________________________________________________ Hexadecimal ________________________________________________________ Operations __________________________________________________________ Examples ____________________________________________________________ Assembly and machine languages _______________________________________ Assignments _________________________________________________________ 5 5 5 5 5 6 8 9 DATA ORGANIZATION __________________________________________ Structure __________________________________________________________ Signed and Unsigned Numbers ________________________________________ Bit Fields and Packed Data ___________________________________________ The ASCII Character Set _____________________________________________ Sign extension and contraction ________________________________________ 10 10 10 12 12 12 BOOLEAN VALUES AND BOOLEAN ALGEBRA _____________________ Boolean Operation on bits ____________________________________________ Boolean theories ____________________________________________________ Example ___________________________________________________________ Assignments ________________________________________________________ 13 13 13 14 15 SYSTEM ORGANIZATION _______________________________________ 16 System Bus ___________________________________________________________ Data bus ___________________________________________________________ Address bus ________________________________________________________ Control Bus ________________________________________________________ System Clock _______________________________________________________ Synchronization_____________________________________________________ 16 16 17 17 18 18 THE 80X86 CPUS VIEW _________________________________________ Registers ___________________________________________________________ Segment and offset __________________________________________________ Logical address to physical address ____________________________________ 19 19 19 20 80X86 COMMANDS _____________________________________________ 21 D:\612925830.doc 2 MOV : copy form source to destination ___________________________________ Example: ___________________________________________________________ ADD : add source to destination _________________________________________ Example: ___________________________________________________________ SUB _______________________________________________________________ Example: ___________________________________________________________ INC : Increment _____________________________________________________ Example: ___________________________________________________________ DEC : decrement _____________________________________________________ Example: ___________________________________________________________ AND bitwise AND ___________________________________________________ Example: ___________________________________________________________ OR ________________________________________________________________ Example: ___________________________________________________________ XOR ______________________________________________________________ Example: ___________________________________________________________ NOT: invert all bits ___________________________________________________ Example: ___________________________________________________________ SHR : shift to the right by one bit ________________________________________ Example: ___________________________________________________________ SHL : shift to the LEFT by one bit _______________________________________ Example: ___________________________________________________________ Your first assembly program __________________________________________ Assignments ________________________________________________________ CMP with JUMP (JE, JNE, JL, JNL, JLE, JG, JNG, JGE , JMP) _______________ Examples: __________________________________________________________ Assignments ________________________________________________________ 21 21 21 21 22 22 22 22 22 22 23 23 23 23 23 23 23 24 24 24 24 24 24 25 26 26 30 WORKING WITH STRING AND ARRAY (ADDRESSING) _______________ 32 Addressing modes _____________________________________________________ 1- Direct Addressing Modes ___________________________________________ 2- Indirect Addressing Modes _________________________________________ 3- Indexed Addressing Modes _________________________________________ 4- Based Indexed Addressing Modes____________________________________ example ____________________________________________________________ Read a string using int21h and function 0ah_______________________________ LODSB (load string in bytes) ___________________________________________ MOVSB (move string in bytes) _________________________________________ REP (repeat until CX = 0) _____________________________________________ REPE with CMPSB (repeat if the compare equals and cx is not zero) ___________ EXAMPLES ________________________________________________________ Assignments ________________________________________________________ 32 32 32 32 33 33 34 36 36 36 37 39 41 MULTIPLICATION AND DIVISION _________________________________ 42 DIV _______________________________________________________________ 42 D:\612925830.doc 3 MUL ______________________________________________________________ 43 Examples ___________________________________________________________ 43 WORKING WITH THE STACK_____________________________________ Stack concept and mechanism _________________________________________ PUSH _____________________________________________________________ POP _______________________________________________________________ 46 46 47 47 Procedures ___________________________________________________________ 50 Numeric to string _____________________________________________________ 51 String to numeric _____________________________________________________ 51 String to numeric _____________________________________________________ 52 Assignments ________________________________________________________ 53 WORKING WITH FILES __________________________________________ Open file ___________________________________________________________ Example ___________________________________________________________ Create file __________________________________________________________ Close file ___________________________________________________________ Read from a file _____________________________________________________ Assignments ________________________________________________________ 54 54 54 54 55 57 60 WORKING WITH THE SCREEN ___________________________________ 61 Examples ___________________________________________________________ 61 WORKING WITH VGA ___________________________________________ Display Modes ______________________________________________________ Memory and screen mapping for mode 13h ______________________________ Examples ___________________________________________________________ Assignments ________________________________________________________ 64 64 65 66 67 APPENDIX ____________________________________________________ 71 D:\612925830.doc 4 Numbering Systems Representation of numbers Before we begin to understand how to program in assembly it is best to try to understand how numbers are represented in computers. Numbers are stored in binary Numbers!. Let’s begin with the most commonly used numbering systems and see why computers use the binary numbers among all others numbering system. Decimal Base is 10 0123456789 Base is 2 01 Binary Hexadecimal Base is 16 0123456789ABCDEF Operations In all numbering systems we can do arithmetic operations like addition subtraction and multiplication: 1-Decimal addition 1+2=3 1+3=4 1 + 9 =10 3 + 9 = 12 2- Binary addition 1+0=1 1 + 1 = 10 3- Hex addition 1+9=A 1+E=F 1 + F = 10 D:\612925830.doc 5 Binary/ Decimal/ Hex conversion table from 0 to 15 Binary(4 digits) Hex(1 digit) Decimal(2 digits) 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 EXAMPLES Given the following decimal numbers, Use binary and hex to do the following arithmetic operation: (1) 34+30 (2) 19+12 (3) 34-30 (1)Binary 34 (0010 0010) 30 (0001 1110) 34 17 8 4 2 1 0 0 L.O 1 0 0 0 1 H.O 30 15 7 3 1 0 0 1 1 1 1 0010 0010 0001 1110 -------------0100 0000 D:\612925830.doc 6 (2)Binary 19 9 4 2 1 0 19 (0001 0011) 12 (0000 1100) 0001 0011 0000 1100 -------------0001 1111 (1) Hex 0010 0010 0001 1110 -------------0100 0000 2 2 1 E ----4 0 (2) Hex 0001 0011 0000 1100 -------------0001 1111 1 3 0C ----1F 1 1 0 0 1 12 6 3 1 0 0 0 1 1 (3) Binary 34-30 =34+(-30) 0010 0010 - 0001 1110 = 0010 0010 + (two’s complement of 0001 1110) two’s complement of 0001 1110 = one’s complement +1 one’s complement == inversion of 1 to 0 (30) (1’s comp) (2’s comp ) 0001 1110 1110 0001 1110 0001+1= 1110 0010 (-30) 1110 0010 finally (34-30) is 0010 0010 1110 0010 -------------0000 0100 D:\612925830.doc 7 Assembly and machine languages Analogy to get more insight for machine and assembly languages Red Yellow Blue Switches fig 1 The assembly language consists of the following 14 operations: Function (Assembly instruction) mix red mix yellow mix blue mix purple mix green mix orange mix black mix white Paint move left move right move forwards move backwards halt Controls value (Machine Language) A B C D E F G 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 Table 1 Mix means dispense paint into the funnel, where it will mix itself. D:\612925830.doc 8 Paint means snap open the valve on the bottom of the funnel, so it will paint the pixel on the piece of paper that is currently under the funnel. Move means move the paper one pixel either left-right or forward-backward. ASSIGNMENTS [1] -Calculate the following operations: 1) 10011011b - 00011010b 2) 2374h + 56A3h 2) 13FFh + 0FA8h 4) 00110111b - 01001001b 4) 36 – 31 in binary [2] – For figure #1, write a short program draw a horizontal line with orange color and length 5 pixels. The program should be in machine and assembly language shown in table1. D:\612925830.doc 9 Data Organization Bit 0 Structure Binary Digit (BIT) Byte Byte 1 BYTE 0 0 0 0 0 0 0 0 0 0 0 0 0 2 NIBBLES 8 BITS 1 WORD 0 0 0 0 0 0 0 0 0 0 0 2 BYTES 4 NIBBLES 16 BITS Signed and Unsigned Numbers In general, with n bits we can represent the signed values in the range -2n-1 to +2n-1-1 or unsigned values in the range 0 to 2n D:\612925830.doc 10 For 16-bit numbers: 8000h is negative because the H.O. bit is one. 100h is positive because the H.O. bit is zero. 7FFFh is positive. FFFFh is negative. 0FFFh is positive. To convert a positive number to its negative, two’s complement form, you use the following algorithm: 1) Invert all the bits in the number, i.e., apply the logical NOT function. 2) Add one to the inverted result. For example, to compute the eight bit equivalent of -5: 0000 0101 Five (in binary). 1111 1010 Invert all the bits. 1111 1011 To convert the numbers above to their negative counterpart (i.e., to negate them), do the following: 7FFFh: 0111 1111 1111 1111 1000 0000 0000 0000 1000 0000 0000 0001 +32,767 Invert all the bits (8000h) Add one (8001h or -32,767t) 8000h: 1000 0000 0000 0000 0111 1111 1111 1111 1000 0000 0000 0000 -32,768 Invert all the bits (7FFFh) Add one (8000h or -32768t) 4000h: 0100 0000 0000 0000 1011 1111 1111 1111 1100 0000 0000 0000 16,384 Invert all the bits (BFFFh) Add one (0C000h or -16,384t) Note: we don’t write the +ive equivalent in signed numbered. Instead we use the two’s complement to use the same H/W and algorithm for both signed and unsigned D:\612925830.doc 11 Bit Fields and Packed Data 0100 00010 1011000 = 0100 0001 0101 1000b or 4158h 4 2 88 The ASCII Character Set A code number to represent each character in the keyboard ASCII Code is 69 ASCII Code is 101 The ASCII codes of the numeric digit characters: Char (shape) “0” “1” “2” “3” “4” “5” “6” “7” “8” “9” Dec 48 49 50 51 52 53 54 55 56 57 Hex 30h 31h 32h 33h 34h 35h 36h 37h 38h 39h Sign extension and contraction 1- Examples of sign extension: 8 Bits 80h 28h 9Ah 7Fh D:\612925830.doc 16 Bits FF80h 0028h FF9Ah 007Fh 32 Bits FFFFFF80h 00000028h FFFFFF9Ah 0000007Fh 12 2- extend an unsigned number 8 Bits 80h 28h 9Ah 7Fh 16 Bits 0080h 0028h 009Ah 007Fh 32 Bits 00000080h 00000028h 0000009Ah 0000007Fh 3- sign contraction FF80h can be sign contracted to 80h 0040h can be sign contracted to 40h FE40h cannot be sign contracted to 8 bits. 0100h cannot be sign contracted to 8 bits. The rule : bytes you wish to remove must all contain either 00h or FFh. Boolean values and Boolean algebra True 1 False 0 Boolean Operation on bits 1- AND 0 and 0 = 0 0 and 1 = 0 1 and 0 = 0 1 and 1 = 1 2- OR 0 or 0 = 0 0 or 1 = 1 1 or 0 = 1 1 or 1 = 1 3- XOR 0 xor 0 = 0 0 xor 1 = 1 1 xor 0 = 1 1 xor 1 = 0 Boolean theories With “ • “ represents AND With “ + “ represents OR With “A’ “ represents NOT A With “ + “ represents OR D:\612925830.doc 13 Th1: Th2: Th3: Th4: Th5: Th6: Th7: Th8: Th15: Th16: A+A=A A•A=A A+0=A A•1=A A•0=0 A+1=1 (A + B)’ = A’ • B’ (A • B)’ = A’ + B’ A + A’ = 1 A • A’ = 0 W = AB X=A+B Y = A’B + AB’ Z = A’ A and B A or B A xor B Not A EXAMPLE ABC+A’BC+AB’C+A’B’C+ABC’ = BC(A+A’) + B’C(A+A’) + ABC’ = BC•1 +B’C•1 + ABC’ = C(B+B’) + ABC’ = C + ABC’ in C++ we can express the above Boolean expression as if(C || (A && B && !C) ) { ... } D:\612925830.doc 14 ASSIGNMENTS - Sign extend the following hex numbers to 16-bits. a) 5F b) 9F c) F3 d) D1 e) 04 f) F2 - Sign contract the following hex numbers to 16-bits and indicate the invalid contraction. a) FF8F b) 8080 c) 0DF3 d) 209D e) 007D f) FFFF 1-Indicate which one of the following 16-bit numbers is positive and which one is negative. a) 8000h b) 100h c) 7FFFh d) 0FFFFh e) 0FFFh - Perform the bitwise AND operation on the following pairs of hex numbers. Present the output in hex a) 0FF00, 0FF0 b) 0F00F, 1234 d) 2F41, F241 c)FFFF,EDCB f) 1111, 5789 - Simplify the following Boolean expression ABC+A’BC+AB’C+B’C+BC’+A’ D:\612925830.doc 15 System Organization The typical Von-Newman architecture is shown below indicating three main units CPU, Memory and I/O Devices. The connection between them is called System Bus System bus System Bus System Bus consists of Data Bus Control Bus Address Bus Data bus To convey data between CPU, memory and I/O devices D:\612925830.doc 16 Address bus To identify the source and/or destination Control Bus D:\612925830.doc 17 System Clock Synchronization D:\612925830.doc 18 The 80x86 CPUs View Registers 2345- General purpose registers Segment registers Pointer register Flag register Code Segment Register 16-bits registers CS Data Segment Register DS Stack Segment Register SS Extra Segment Register ES Segment and offset Segment on 80x86 can form 64K byte to 4 gigabyte. Offset is used to point inside the segment. The memory can be seen as 2-D array as shown in the figure below D:\612925830.doc 19 Logical address to physical address The following figure shows how to calculate the physical address from the logical address. D:\612925830.doc 20 80X86 commands MOV : copy form source to destination mov mov mov mov mov mov mov mov reg(8,16),reg(8,16) reg,mem reg, value mem,reg segreg,mem segreg,reg reg,segreg mem,segreg In all cases, check the size (8,16,32) EXAMPLE: mov ax,12 mov ax,12h mov al,0 mov var1,90 mov var2,00010100b ADD : add source to destination add add add add add reg,reg reg,mem mem,reg mem,value reg, value In all cases, check the size EXAMPLE: add ax,12 add ax,12h add al,ah add var1,90 add var2,00010100b D:\612925830.doc 21 SUB sub sub sub sub sub reg,reg reg,mem mem,reg mem,value reg, value In all cases, check the size EXAMPLE: sub ax,12 sub ax,12h sub al,ah sub var1,90 sub var2,00010100b INC : Increment inc reg inc mem EXAMPLE: inc ax inc var1 DEC : decrement dec reg dec mem EXAMPLE: dec ax dec var1 D:\612925830.doc 22 AND bitwise AND and and and and reg,reg mem,reg reg,mem reg,value EXAMPLE: and al,bl and al,00010010b and var,32h OR or or or or reg,reg mem,reg reg,mem reg,value EXAMPLE: or al,bl or al,00010010b or var,32h XOR xor xor xor xor reg,reg mem,reg reg,mem reg,value EXAMPLE: xor al,bl xor al,00010010b xor var,32h NOT: invert all bits not reg not mem D:\612925830.doc 23 EXAMPLE: not al not var1 SHR : shift to the right by one bit shr shr shr shr reg,number mem,number reg,cl mem,cl EXAMPLE: shr shr shr shr al,1 ax,1 var1,1 var1,cl SHL : shift to the LEFT by one bit shl shl shl shl reg,number mem,number reg,cl mem,cl EXAMPLE: shl shl shl shl al,1 ax,1 var1,1 var1,cl Your first assembly program Write a program to calculate the following: W=x + y – z D:\612925830.doc 24 .model small .data x db 10 y db 3 z db 5 w db ? d .code main: mov ax,@data mov ds,ax Mov Add sub Mov al,x al,y al,z w,al mov ah,4ch int 21h end main ASSIGNMENTS [1]- Write a statement for each of the following tasks: - Clear all bits of AX except nibble 3 - Change bit 0 and bit 7 of AH - Set all bits of AH except bit 3 [2] Write the following expressions in assembly language using shifts, additions and subtraction only. a) CX * 7 b) BX * 129 c) AX * 512 d) AX / 8 [3] Write a statement for each of the following tasks -clear all bits of AX except nibble 3 -change bit 0 and bit 7of AH e) BX * 5 [3] Write a program to compute the result of ABC’ + ABC + A’B + B’A + C D:\612925830.doc 25 Flow control instructions CMP with JUMP (JE, JNE, JL, JNL, JLE, JG, JNG, JGE , JMP) cmp reg,number je lable1 cmp mem,number jle lable jmp lable EXAMPLES: loop1: EndLoop: mov cmp jle dec jmp ----- al,10 al,0 EndLoop al loop1 int x=10; while(x>0) { x--; } Some examples using CMP , JUMP and LOOP for(int i=0;i<100;i++) { var1++; } loop1: mov cl,100 inc var1 loop loop1 In this case we know the limit of the loop D:\612925830.doc 26 for(int i=start;i<stop;i++) { var1++; } mov cl,stop sub cl,start jl SkipFor inc var1 loop loop1 loop1: SkipFor: General case int i=0; while(i<100) { var1++; i++; } loop1: mov cmp jge inc inc jmp al,0 al,100 LoopDone var1 al loop1 Loop1Done: Some other loops (using JZ, JS, JC, JNZ, JNS, JNC) For(int i = 1 ;i<= 8; i++) { k = k + i - j; } FLP: mov mov add sub mov inc cmp jle D:\612925830.doc i, 1 ax, k ax, i ax, j k, ax i i, 8 FLP For(int i = 8 ;i>=1; i++) { k = k + i - j; } FLP: mov mov add sub mov dec jnz i, 8 ax, k ax, i ax, j k, ax i FLP 27 IF THEN ELSE control IF (a==b) { c = d ; } mov cmp jne mov mov ax, a ax, b EndOfIf bx, d c, bx mov cmp jne mov mov jmp ax, a ax, b ElseBlk bx, d c, bx EndOfIf EndOfIf: IF (a==b) { c = d ; } else { b = b + 1; } ElseBlk: inc b EndOfIf: Control examples IF ((X > Y) && (Z < T)) { C = D; } IF (X > Y) { IF(Z < T) { C = D; } } D:\612925830.doc mov cmp jng mov cmp jnl mov mov ax, x ax, y EndOfIf ax, z ax, t EndOfIf bx,d c,bx EndOfIf: 28 IF ((X > Y) && (Z < T))|| (A!=B) { C = D; } mov cmp jne mov cmp jng mov cmp jnl ax ,a ax,b DoIf ax, x ax, y EndOfIf ax, z ax, t EndOfIf DoIf: mov bx,d mov c,bx EndOfIf: 1- Check if a given number is odd or even int num ; cin>>num if((num%2)==0) { cout<<”it is an even ”; } else { cout<<”it is an even ”; } mov al,num ; and al,00000001b jnz OddNum code to Print even OddNum: Code to Print odd 2- Print a character on screen using interrupt mov ah,02h mov dl,’A’ int 21h D:\612925830.doc 29 3- Print a number within 0-9 mov mov add int dl,5 ah,02h dl,30h 21h ASSIGNMENTS [1]- Convert the following C statement to assembly language a. if (x==0) && ((y-2) > 1) { y --; } b. if ((X > Y) && (Z < T))|| (A!=B) { C = D; } c. if ((X *5)>100) && (Y / 4))<100)) { C = D; } [2]- Trace DL and Y .model small .data stop db 10 start db 5 y db 0 .code prog: mov ax,@data mov ds,ax mov cl,stop sub cl,start jl SkipFor loop1: inc y loop loop1 SkipFor: mov ah,02 mov dl,y or dl, 30h D:\612925830.doc 30 int 21h mov ah,4ch int 21h end prog [3] - Print character from a-z D:\612925830.doc 31 Working With String and Array (Addressing) Addressing modes 1- Direct Addressing Modes MOV al,ds:[14F0h] Or simply MOV ax,[14F0h] 2- Indirect Addressing Modes Using register (BX, SI, DI and BP only) the first three assume to use DS by default and last one uses SS as its default segment Mov Mov Mov Mov al, al, al, al, [bx] [bp] [si] [di] However, you can use another segment instead of the default segment Mov Mov Mov Mov al, al, al, al, cs:[bx] ds:[bp] ss:[si] es:[di] 3- Indexed Addressing Modes The indexed addressing modes use the following syntax: mov mov mov mov al, al, al, al, disp[bx] disp[bp] disp[si] disp[di] If bx contains 1000h, then the instruction mov cl,20h[bx] will load cl from memory location ds:1020h. Likewise, if bp contains 2020h, mov dh,1000h[bp] will load dh from location ss:3020. D:\612925830.doc 32 4- Based Indexed Addressing Modes mov mov mov mov al, al, al, al, [bx][si] [bx][di] [bp][si] [bp][di] EXAMPLE .model small .data x DB 1,2,3,4,5,6 y DB 3 var1 DB 5 .code START: MOV AX,@data MOV DS,AX LEA BX,x ; load Effective address ;indirect mode MOV DL,DS:[BX] MOV AH,02h ADD DL,'0' INT 21h 1 ;indexed mode MOV DL,[BX+3] MOV AH,02h ADD DL,'0' INT 21h 4 ;indexed mode MOV DL,DS:05h[BX] MOV AH,02h ADD DL,'0' INT 21h 6 ;based indexed mode MOV SI,0h MOV DL,[BX][SI] MOV AH,02h ADD DL,'0' INT 21h 1 MOV AH,4ch INT 21h end start D:\612925830.doc 33 - Read a string using int21h and function 0ah Define label (structure) REP, REPE,REPNE LODSB MOVSB CMPSB READ A STRING USING INT21H AND FUNCTION 0AH plist1 label byte mlen1 db 10 alen1 db ? str1 db 10 dup(' '), 'S' ... ... mov ah,0ah lea dx,plist1 int 21h D:\612925830.doc 34 - Write a program to read a string and then search about given character .data plist1 label byte mlen1 db 10 alen1 db ? str1 db 10 dup('$') msg1 db 'found','$' msg2 db 'not found','$' .code main: mov ax,@data mov ds,ax mov es,ax mov ah,0ah lea dx,plist1 int 21h mov al, ‘s’ lea bx,str1 wlp: cmp [bx],al je found inc bx loop wlp mov lea int jmp ah,09h dx,msg2 21h endprog found: mov ah,09h lea dx,msg1 int 21h endprog: mov ah,4ch int 21h end main D:\612925830.doc 35 LODSB (LOAD STRING IN BYTES) plist1 label byte mlen1 db 10 alen1 db ? str1 db 10 dup(' '), 'S' ... ... lea si,str1 loadsb mov al,[si] inc si MOVSB (MOVE STRING IN BYTES) Copy one string to another ... ... lea si,str1 lea di,str2 movsb mov [di],[si] inc si inc di REP (REPEAT UNTIL CX = 0) ... mov lea lea rep D:\612925830.doc cx,8 si,str1 di,str2 movsb lp: mov inc inc dec cmp jg [di],[si] si di cx cx,0 lp 36 REPE WITH CMPSB (REPEAT IF THE COMPARE EQUALS AND CX IS NOT ZERO) Write a program to compare 2-strings of equal length .data str1 db 'assembly','$' str2 db 'assembly','$' msg1 db 'equal','$' msg2 db 'not equal','$' .code st: mov ax,@data mov ds,ax mov es,ax mov cx,8 lea si,str1 lea di,str2 mov cx,8 repe cmpsb je equal notequal: lea dx,msg2 mov ah,09 int 21h jmp endprog equal: lea dx,msg1 mov ah,09 int 21h endprog: mov ah,4ch int 21h end st D:\612925830.doc 37 - Print a string .model small .data str1 db ‘Hello world’,’$’ .code start: mov ax,@data mov ds,ax lea dx, str1 mov ah,09 int 21h mov ah,4ch int 21h end start - Working with a string (print string using a loop) .model small .data str1 db 'Hello world','$' .code start: mov ax,@data mov ds,ax lea di, str1 mov cx,11 mov ah,02 flp: mov dl,[di] int 21h inc di loop flp mov ah,4ch int 21h end start D:\612925830.doc 38 4- Working with array Array definition x db 0,1,2,3,4,5,6,7,8,9 x db size dup(value) EXAMPLES .model small .data x db 0,1,2,3,4,5,6,7,8,9 .code st: mov ax,@data mov ds,ax lea bx,x mov cx,10 l1: mov mov add int ah,02h dl,[bx] dl,'0' 21h cont: inc bx loop l1 mov ah,4ch int 21h end st .model small .data x db 10 dup(3) .code st: mov ax,@data mov ds,ax lea bx,x mov cx,10 l1: mov ah,02h sub [bx],1 mov dl,[bx] add dl,'0' int 21h cont: inc bx loop l1 mov ah,4ch int 21h end st D:\612925830.doc 39 - Write a program to print the binary repetition of the 2’s complement of a given number .model small .data num db 07 mask db 10000000b .code st: mov ax,@data mov ds,ax mov cx,8 mov al,num not al add al,1 flp: and al,mask jz printzero printone: mov dl,'1' mov ah,02h int 21h shr mask,1 loop flp jmp endprog printzero: mov dl,'0' mov ah,02h int 21h shr mask,1 loop flp endprog: mov ah,4ch int 21h end st D:\612925830.doc 40 ASSIGNMENTS - Write a program to print 16-bits number in hexadecimal format - As shown below the ASCII of character ‘R ‘ differs only from character ‘r’ at bit 5, how can you quickly convert from upper to lower and from lower to upper based on the above fact. R 7 0 6 1 5 0 4 0 3 0 2 1 1 1 0 1 r 7 0 6 1 5 1 4 0 3 0 2 1 1 1 0 1 - Write a program that reads a string from the user, reverses the 2nd half of the string and prints it on the screen. D:\612925830.doc 41 Multiplication and division DIV 1- word/byte Quotient AH:AL AL DIV AH MEM/REG int x=230; int y=5; int z=x/y; 2- word/word Reminder X dw 230 Y db 5 ... mov ax,x div y mov z, al DX:AX AX DIV DX MEM/REG D:\612925830.doc 42 MUL 1- Byte * byte ax = al * reg/mem AL MUL AX MEM/REG 2- word *word dx:ax=ax * reg/mem DX:AX MUL DX:AX MEM/REG int x=130; int y=5; int z=x*y; x db 130 y db 5 ... mov ax,x mul y mov z, ax EXAMPLES - Write a program to calculate x = (a+b)*(c/d) .model .data x dw a db b db c db d db small ? 2 3 10 2 .code st: mov ax,@data mov ds,ax mov bl,a D:\612925830.doc 43 add bl,b mov al,c mov ah,0 div d mul bl mov x,ax mov ah,4ch int 21h end st - Write a program to calculate W=(x+y)/(z+t) (use w as 16-bits) Xor Mov Add Mov Add Div Mov dx,dx ax,x ax,y bx,t bx,z bx w,ax - Write a program to print only the even number from a given array (assume the numbers if the array within 0-9) .model small .data x db 0,1,2,3,4,5,6,7,8,9 x1 db 2 .code st: mov ax,@data mov ds,ax lea bx,x mov cx,10 l1: mov al,[bx] mov ah, 0 div x1 cmp ah,0 jne cont mov mov add int ah,02h dl,[bx] dl,'0' 21h cont: inc bx loop l1 D:\612925830.doc 44 mov ah,4ch int 21h end st - Write a program to calculate the factorial res=n*(n-1)*(n-2)…. * (1) title fact .model small .data x db 5 res dw 1 .code start: mov ax , @data mov ds,ax l1: mov al,x mov ah,0h mul res mov res,ax dec x cmp x,1 jg l1 end1: mov ah,4ch int 21 end start D:\612925830.doc 45 Working with the Stack Stack concept and mechanism Stack is a special memory area used to store data temporarily when calling a subprogram and nested loops. Stack mechanism works in style “Last In First Out” LIFO. The following figure shows the stack mechanism. PUSH AX Stack is empty PUSH AX 3 8 3 3 8 Sp=2 Sp=1 Sp=0 POP BX 3 POP BX 8 3 Sp=1 Sp=0 D:\612925830.doc 46 The process of calling a subprogram is shown below mov al,x mov ah,0h mul res mov res,ax dec x cmp x,1 jg l1 call subprog mov ah,0h mul res mov res,ax call subprog cmp x,1 jg l1 mov mov mul mov dec al,y ah,0h res res,ax y PUSH push REG/MEM 16-bits only push ax Increment SP register and store AX in the top of stack memory area POP pop REG/MEM 16-bits only pop bx D:\612925830.doc copy the value in the top of stack to BX then remove it and decrement SP register 47 - write a program for the c code .model small .data res db 0 .code st: mov cx,10 flp1: Res=0; for(int i=0;i<10;j++) { for(int j=0;j<5;j++) { res+=j; } } push cx mov cx,5 flp2: add res,cx loop flp2 pop cx loop flp1 ... -Write a program to use the stack to determine if a given string is palindrome .model small .stack 46h .data str1 db 'mooom' msg1 db 'is pal','$' msg2 db 'is not pal','$' st: mov ax,@data mov ds,ax lea si,str1 mov cx,5 flp1: mov al,[si] mov ah,0 push ax inc si loop flp1 D:\612925830.doc 48 lea si,str1 mov cx,5 flp2: pop ax cmp al,[si] jne notpal inc si loop flp2 pal: mov lea int jmp notpal: mov lea int endprog: mov int end D:\612925830.doc ah,09h dx,msg1 21h endprog ah,09h dx,msg2 21h ah,4ch 21h st 49 Procedures - Write a program to print a string .model small .data num db 4 str1 db ‘hello’,’$’ .code prog: main proc near mov ax,@data mov ds,ax call printme mov ah,4ch int 21h endp main printme proc lea dx,str1 mov ah,09h int 21h ret endp printme end prog D:\612925830.doc 50 Numeric to string AL 251 11111011 Print AL How to convert to string ‘2’ ‘5’ ‘1’ - Repeat integer division by 10 and take the remainder o 251/10 = 25 and r = 1 o 25/10 = 2 and r = 5 o 2/10 and r = 2 =0 3267 o 3267/10 = 326 and r = 7 o 326/10 = 32 and r = 6 o 32/10 =3 and r = 2 o 3/10 =0 and r = 3 .model small .data stringval db 4 dup(' '),'$' binval dw 1034 tostring lea mov mov proc near si, stringval+3 cx,10 ax,binval l1: cmp ax,cx jb l2 xor dx,dx div cx or dl,30h mov [si],dl dec si jmp l1 l2: or al,30h mov [si],al ret tostring endp D:\612925830.doc 51 String to numeric ‘5245’ to 5245 5245= 5 * (10)3 + 2 * (10)2 + 4 * (10)1 + 5 * (10)0 ‘5245’= [35h-30h] * (10)3 + [32h-30h] * (10)2 + [34h-30h] * (10)1 + [35h-30h] * (10)0 .model small .data strvaldb 10 dup('1234') binval dw 0 mulfactor dw 1 .code prog: mov ax,@data mov ds,ax mov es,ax mov bx, 10 mov cx,4 lea si,asciival+3 lp1: mov sub mov mul add al[si] al,30h ah,0 mulfactor binval,ax mov ax,mulfactor mul bx mov mulfactor,ax dec si loop lp1 mov ah,4ch int 21h end prog D:\612925830.doc 52 ASSIGNMENTS - Write a program to read 2-numbers form the user then add them and print the result - Write a program to read a number from the user and then print two’s complement in binary format - Write a program to check if a given string is well formed or ill formed according to the following table. The table shows some examples of ill formed expression in terms of (), {}, [] constructions. Well-formed Ill-formed For(i=0; i<10; i++){y++;} For(i=0; i<10; i++){y++;}} While(true); while(true){; If(i=9){{res+=10;};} If(i=9)}{res+=10;};} int i[100]; int y=0;;; int i[100); int y=0;;; D:\612925830.doc 53 Working with Files Open file Function (AH): 3Dh Entry parameters: AH - file access value 0- File opened for reading 1- File opened for writing 2- File opened for reading and writing DS:DX- Point at a zero terminated string containing the filename. Exit parameters: If the carry is set, AX contains one of the following error codes: 1- File not found 4- Too many open files 5- Access denied 12- Invalid access If the carry is clear, AX contains the file handle value assigned by DOS. A file must be opened before you can access it. The open command opens a file that already exists. Attempting to open a file that doesn’t exist produces an error. EXAMPLE Filename DB 'test.txt',0 FileHandle DW ? ... lea dx, Filename mov ah, 3dh mov al, 0 ;Open for reading. int 21h jc OpenError mov FileHandle, ax Create file Function (ah): 3Ch Entry parameters: ds:dx- Address of zero terminated pathname cx- File attribute Exit parameters: If the carry is set, ax contains one of the following error codes: 3- Path not found 4- Too many open files D:\612925830.doc 54 5- Access denied If the carry is clear, ax is returned containing the file handle Create opens a new file for output. As with the OPEN command, ds:dx points at a zero terminated string containing the filename. Since this call creates a new file, DOS assumes that you’re opening the file for writing only. Another parameter, passed in cx, is the initial file attribute settings. The L.O. six bits of cx contain the following values: Bit Meaning if equal to one 0 File is a Read-Only file 1 File is a hidden file 2 File is a system file 3 File is a volume label name 4 File is a subdirectory 5 File has been archived In general, you shouldn’t set any of these bits. Most normal files should be created with a file attribute of zero. Therefore, the cx register should be loaded with zero before calling the create function. Upon exit, the carry flag is set if an error occurs. The “Path not found” error requires some additional explanation. This error is generated, not if the file isn’t found (which would be most of the time since this command is typically used to create a new file), but if a subdirectory in the pathname cannot be found. If the carry flag is clear when DOS returns to your program, then the file has been properly opened for output and the ax register contains the file handle for this file. Close file Function (ah): 3Eh Entry parameters: bx- File Handle Exit parameters: If the carry flag is set, ax contains 6, the only possible error, which is an invalid handle error. This call is used to close a file opened with the Open or Create commands above. It is passed the file handle in the bx register and, assuming the file handle is valid, closes the specified file. You should close all files your program uses as soon as you’re through with them to avoid disk file corruption in the event the user powers the system down or resets the machine while your files are left open. Note that quitting to DOS (or aborting to DOS by pressing control-C or control-break) automatically closes all open files. However, you should never rely on this feature since doing so is an extremely poor programming practice. D:\612925830.doc 55 - Create a new file and close file .model small .data Filename db 'test00.txt',0 FHndl dw ? .code prog: mov ax,@data mov ds,ax mov cx,0 mov ah, 3ch ;Open the file mov al, 0 ;Open for reading lea dx, Filename int 21h jc BadOpen mov FHndl, ax ;Save file handle EOF: mov bx, FHndl mov ah, 3eh int 21h jc CloseError ;Close file CloseError: ... BadOpen: ... mov ah,4ch int 21h end prog D:\612925830.doc 56 Read from a file Function (ah): 3Fh Entry parameters: bx- File handle cx- Number of bytes to read ds:dx- address of array large enough to hold bytes read Exit parameters: If the carry flag is set, ax contains one of the following error codes 5- Access denied 6- Invalid handle If the carry flag is clear, ax contains the number of bytes actually read from the file. The read function is used to read some number of bytes from a file. The actual number of bytes is specified by the cx register upon entry into DOS. The file handle, which specifies the file from which the bytes are to be read, is passed in the bx register. The ds:dx register contains the address of a buffer into which the bytes read from the file are to be stored. On return, if there wasn’t an error, the ax register contains the number of bytes actually read. Unless the end of file (EOF) was reached, this number will match the value passed to DOS in the cx register. If the end of file has been reached, the value return in ax will be somewhere between zero and the value passed to DOS in the cx register. - write a program to read file and print its contents .model small .data Filename db 'test.txt',0 FHndl dw ? Buffer db ? .code prog: mov ax,@data mov ds,ax mov ah, 3dh ;Open the file mov al, 0 ;Open for reading lea dx, Filename;Presume DS points at filename int 21h jc BadOpen mov FHndl, ax ;Save file handle D:\612925830.doc 57 LP: mov ah,3fh lea dx, Buffer mov cx, 1 mov bx, FHndl int 21h jc ReadError ;Read data from the file ;Address of data buffer ;Read one byte ;Get file handle value cmp ax, cx jne EOF ;EOF reached? mov ah,02h mov dl,Buffer int 21h ;print charcrter ;the character to print jmp LP ;Read next byte EOF: mov bx, FHndl mov ah, 3eh int 21h jc CloseError ;Close file CloseError: ... ReadError: ... BadOpen: ... mov ah,4ch int 21h end prog D:\612925830.doc 58 - write a program to read a file and put the content in a string .model small .data Filename db 'test.txt',0 FHndl dw ? Buffer db ? filedata db 1024 dup('$') .code prog: mov ax,@data mov ds,ax lea di,filedata mov ah, 3dh ;Open the file mov al, 0 ;Open for reading lea dx, Filename;Presume DS points at filename int 21h jc BadOpen mov FHndl, ax ;Save file handle LP: mov ah,3fh lea dx, Buffer mov cx, 1 mov bx, FHndl int 21h jc ReadError ;Read data from the file ;Address of data buffer ;Read one byte ;Get file handle value cmp ax, cx jne EOF ;EOF reached? mov dl,Buffer mov [di],dl inc di jmp LP ;Read next byte EOF: mov bx, FHndl mov ah, 3eh int 21h jc CloseError ;Close file CloseError: ... ReadError: ... BadOpen: ... D:\612925830.doc 59 mov ah,09h lea dx,filedata int 21h mov ah,4ch int 21h end prog ASSIGNMENTS 1- Write a program to display a file on the screen page by page based on the user hits on the keyboard 2- Write a program to copy an existing file into a new file 3- Write a program to display only the last 10 lines of a file D:\612925830.doc 60 Working with the screen col 1- Setting the courser AH 02h int 10h 0 0 row col BH DH DL 0 79 row 25 2- Clear screen area AH 06H int 10h 00 attribute (row:col) start (row:col) end AL BH CX DX Attributes 7 BL 6 R 5 G Background 4 B 3 I 2 R 1 G 0 B Foreground EXAMPLES - Write a program to clear screen and color it with red .model small .data .code D:\612925830.doc 61 prog: mov mov mov mov mov int ah,06h al,00 bh,01001000b cx,0000h dx,184eh 10h mov ah,4ch int 21h end prog 3- Print character N-times AH int 09H 10h AL BH BL CX character to be printed page # Attribute N - Write a program to display character # 20 times start from col:30 at row 12 .model small .data .code prog: mov mov mov mov mov int mov mov mov mov int D:\612925830.doc ah,06h ;clear screen and color it al,00 bh,01001000b cx,0000h dx,184eh 10h ah,02h bh,0 dh, 12 dl ,30 10h ;set cursor at pos 12,30 62 mov mov mov mov mov int ah,09h ;print # 20 times al,'#' bh,0 bl, 01001001b cx,20 10h mov ah,4ch int 21h end prog D:\612925830.doc 63 Working with VGA Display Modes VGA has several modes: Mode 0 1 2 3 4 5 6 7 Graphics (pixels) 640x200 320x200 Same as mode 1 None 320x200 Same as mode 4 None None Logical Colours 2 colour display 4 colour display Text (chars) 80x25 40x25 16 colour text only 4 colour display 80x25 40x25 16 colour text only Monochrome text only Viewdata emulation 16 colour 16 colour 40x25 80x25 40x25 80x25 40x25 8 9 10 11 12 13 14 15 16 640x200 320x200 Same as mode 9 Same as mode 3 Same as mode 9 Same as mode 9 Same as mode 6 640x350 640x350 monochrome display 16 colour 80x25 80x25 or 80x43 17 18 Reserved for expansion. 640x480 16 colour 80x30 or 80x60 Resolution Colours Memory Required 640 x 400 256 250Kb 640 x 480 256 300Kb 800 x 600 256 469Kb 1024 x 768 256 768Kb 1280 x 1024 256 1.28Mb 640 x 400 65536 500Kb 640 x 480 65536 600Kb 800 x 600 65536 930Kb 1024 x 768 65536 1.5Mb 1280 x 1024 65536 2.5Mb 640 x 400 16.7 million 750Kb 640 x 480 16.7 million 900Kb D:\612925830.doc 64 800 x 600 16.7 million 1.4Mb 1024 x 768 16.7 million 2.25Mb 1280 x 1024 16.7 million 3.75Mb Memory and screen mapping for mode 13h Screen Layout X Memory Location = (Y * Width) + X Y Width Video RAM Layout 0xA000h D:\612925830.doc 65 EXAMPLES 1-Write a program to plot one pixel on location (x,y) using VGA mode 13h Answer .model small .386 .stack 100h .data color db ? .code start: mov ax,@data mov ds,ax Mov ax,0013h int 10h ; start vga mode 13h with BIOS interrupt 10h mov ax,0a000h mov es,ax mov cx,100 mov dx,100 ; set video RAM location(address) into es ; x coordinate ; y coordinate mov color,120 ; color in al call point call keyd mov int mov int ; call procedure to plot point at cx,dx coords ; wait for the user to hit any key ax,0003h ; reset to text mode 3 10h ax,4c00h 21h point: pusha mov ax,320 mul dx add ax,cx mov bx,ax mov al,color mov es:[bx],al popa ret ; key delay procedure - wait for keypress before continuing KEYD: push ax ; save ax register before local use mov ah,1 ;1 DOS interrupt for keyboard input int 21h pop ax ; restore ax ret ; pop saved instruction address and jump end start D:\612925830.doc 66 ASSIGNMENTS 1- Write a program to draw a multi-colored (16 colors only) line in VGA mode 31h 2- Write a program which has trhee procedure to draw : a. horizontal line b. vertical line c. rectangle 3- Write a program to move a rectangle from left to right and reverse D:\612925830.doc 67 4- Assignment # 2 Print a given 16-bits number in hexadecimal format Answer 1 .model small .386 .stack 100h .data ; ascii values of hex digits 0-F asciis db 48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70 endl db ‘H’,13,10,'$' .code prog: mymain proc mov ax,@data mov ds,ax mov cx,26 ; sample value decimal value call printhex mov cx,0abcdh ; simple hex value call printhex mov ax,4c00h int 21h mymain endp ;printhex proc printhex: push ax push bx push dx mov shr lea add mov mov int mov and shr mov add mov int mov and shr mov add mov int mov and mov add mov int ; save registers dx,cx dx,12 ; first 4 bits now can be used as offset bx,asciis ; load the address in bx bx,dx dl,[bx] ah,2 21h ; print the first char dx,cx dx,0F00h ; mask out other 12 bits before shift dx,8 bx,offset asciis bx,dx dl,[bx] 21h ; print second char dx,cx dx,00F0h dx,4 bx,offset asciis bx,dx dl,[bx] 21h ; print the third char dx,cx dx,000Fh bx,offset asciis bx,dx dl,[bx] 21h ; print the last char D:\612925830.doc 68 mov dx,offset endl mov ah,9 int 21h pop dx pop bx pop ax ret ;printhex endp end prog ; print "\n" ; restore registers and return Answer 2 Using a loop .model small .386 .stack 100h .data ; ascii values of hex digits 0-F asciis db 48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70 endl db 'H',13,10,'$' bits db 16 num dw 26 mask1 dw ? .code prog: mymain proc mov ax,@data mov ds,ax ; assume value to be printed is in cx mov cx,48 ; sample value decimal value call printhex mov cx,0abcdh ; simple hex value call printhex mov ax,4c00h int 21h mymain endp ;printhex proc printhex: push ax push bx push dx mov mov mov mov mov ; save registers mask1, 0F000h num,cx dx,cx cx,4 bits,16 l1: push cx sub bits,4 mov cl,bits and dx,mask1 shr dx,cl ; first 4 bits now can be used as offset lea bx,asciis ; load the address in bx add bx,dx D:\612925830.doc 69 mov dl,[bx] mov ah,2 int 21h shr mask1,4 mov dx,num pop cx loop l1 ; print the first char mov dx,offset endl mov ah,9 int 21h pop dx pop bx pop ax ret ;printhex endp end prog D:\612925830.doc ; print "\n" ; restore registers and return 70 Appendix To read a character: Function: 10h in AH Int: 16h Character read will be in AL To print a character: Function: 02h in AH Int: 21h Character to print should be in DL To print a string terminated by $: Function: 09h in AH Int 21h Starting address of the string to print in DX To print a string : Function:: 40h in AH Int: 21h Starting address of the string to print in DX Number of characters to print in CX Setting the cursor at a certain position : Function: 02h in AH Int: 10h Page no. BH Row DH Column DL To scroll a number of lines in the screen: Function: 06h in AH Int: 10h No. of lines to scroll AL Attribute BH Start point CX (row : column) End point DX (row : column) The attribute field is as follows : 0 BLINKING 1 R 2 G 3 B 4 INTENSITY 5 R 6 G 7 B Bits 1, 2, 3 are for the background color Bits 5, 6, 7 are for the foreground color To read a string from the user : Function: 0ah in AH Int: 21h Starting address of the paramter list DX The parameter list should conatin: 1) Maximum length 2) Actual length 3) A place to store the read string in D:\612925830.doc 71 Multiplication: Byte by Byte: Multiplicand AL Multiplier Register/Memory Result AX Word by Word: Multiplicand AX Multiplier Register/Memory Result DX : AX Division: a. Word/ Byte: Dividend AX Divisor Register/Memory Quotient AL Remainder AH b. Double Word/Word: Divident DX :AX Divisor Register/Memory Quotient AX Remainder DX D:\612925830.doc 72