Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0%
(1)
0% found this document useful (1 vote)
396 views
39 pages
Chapter03 Mazidi PDF
Uploaded by
Muhammad Abdullah
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save chapter03_Mazidi (1).pdf For Later
Share
0%
0% found this document useful, undefined
100%
, undefined
Print
Embed
Report
0%
(1)
0% found this document useful (1 vote)
396 views
39 pages
Chapter03 Mazidi PDF
Uploaded by
Muhammad Abdullah
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save chapter03_Mazidi (1).pdf For Later
Share
0%
0% found this document useful, undefined
100%
, undefined
Print
Embed
Report
Download
Save chapter03_Mazidi (1).pdf For Later
You are on page 1
/ 39
Search
Fullscreen
CHAPTER 3 ARITHMETIC AND LOGIC INSTRUCTIONS AND PROGRAMS OBJECTIVES Upon completion of this chapter, you will be able to: Demonstrate how B-bit and 16-bit uusigned numbers are added in the 80x86 Convert data to any of the forms: ASCII, packed BCD, or unpacked BCD Explain the effect of unsigned arithmetic instructions on the flag register ‘Code the following Assembly language unsigned arithmetic instructions: "Addition instruetions ADD and ADC ‘Subtraction instructions SUB and SBB ‘Multiplication amd division instructions MUL-and DIV ‘Code BCD and ASCH arithmetic instructions: DAA, DAS, AAA, AAS, AM, and AAD. Code the following Assembly language logic instructions: AND, OR, and XOR Logical shift instructions SHR and SHL The compare instruction CMP Code BCD and ASCII arithmetic iustractions, Code bitwise rotation instructions ROR, ROL, RCR, and RCL Demonstrate an_ability to use all of the instructions above in Assembly language programs » Perform bitwise manipulation using the C language Ye y eee Y ye Y eee ey 82 CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONS.In this chapter, most of the arithmetic and logic instructions are discussed and program examples are given to illustrate the application of these instructions. Unsigned numbers are used in this discussion of arithmetic and logic instructions. Signed numbers are discussed separately in Chapter 6. Unsigned numbers are defined as data in which all the bits ate used to represent data and no bits are set aside for the positive or negative sign. This means that the operand can be between 00 and FFH (0 to 255 decimal) for 8-bit data and between 0000 and FFFFH (0 to 65535 decimal) for 16-bit data. The last section of the chapter describes bitwise operations in the C language. SECTION 3.1: UNSIGNED ADDITION AND SUBTRACTION Addition of unsigned numbers The form of the ADD instruction is ADD destination,source ;dest. operand = dest. operand + source operand The instructions ADD and ADC are used to add two operands. The desti- nation operand can be a register or in memory. The source operand can be a register, inmemory, or immediate. Remember that memory-to-memory operations are never allowed in 80x86 Assembly language. The instruction could change any of the ZF, SF, AF, CF, or PF bits of the flag register, depending on the operands involved. The effect of the ADD instruction on the overflow flag is discussed in Chapter 6 since it is used in signed number operations. Look at Example 3-1 Example 3-1 Show how the flag register is affected by MOV ALOFSH ADD = ALOBH. Soluti FSH 1111 0104 +0BH + 0000 1011 ‘100H {0000 0000 After the addition, the AL register (destination) contains 00 and the flags are as follows: CF = I since there is a carry out from D7 SF =0 the status of D7 of the result PF = 1 the number of Is is zero (zero is an even number) AP =1 there is a carry from D3 to D4 ZF = 1 the result of the action is zero (for the 8 bits) In discussing addition, the following two cases will be examined: 1. Addition of individual byte and word data 2. Addition of multibyte data CASE 1: Addition of individual byte and word data In Chapter 2 there was a program that added 5 bytes of data, The total sum ‘was purposely kept less than FFH, the maximum value an 8-bit register can hold. To calculate the total sum of any number of operands, the carry flag should be checked after the addition of each operand. Program 3-1a uses AH to accumulate carries as the operands are added to AL. SECTION 3.1; UNSIGNED ADDITION AND SUBTRACTION 83‘Write a program to calculate the total sum of 5 bytes of data. Each byte represents the daily wages of worker. This person docs not make more than $255 (FFH) a day. The decimal data is as follows: 125, 235, 197, 91, and 48. TITLE — PROGS-1A (EXE) ADDING 5 BYTES. PAGE 60.132 MODEL SMALL STACK 64 DATA COUNT EQU 05 DATA 0B 125,235,197,91,48 ORG —0008H sum DW? ‘CODE MAIN PROC FAR MOV AX,@DATA Mov DS\AK MOV CX.COUNT ___:CXis the loop counter MOV — SIOFFSET DATA'SI's the data pointer Mov AX,00 ‘AX will hold the sum BACK = ADD AL{SI] ‘add the next byte to AL. NC OVER “ifno carry, continue INC) AH ‘else accumulate carry in AH over; INC SI ‘increment data pointer DEC cx ‘decrement loop counter NZ BACK 5ifnot finished, go add next byte MOV SUMAX {store sum MOV AH.ACH INT 21H ,90 back to DOS MAIN ENOP END MAIN Program 3-1a 3. Analysis of Program 3-1a ‘These numbers are converted to hex by the assembler as follows: 125 = ‘7DH, 235 = OEBH, 197 = OCSH, 91 = SBH, 48 = 30H. Three iterations of the loop are shown below. The tracing of the program is left to the reader as an exercise. . In the first iteration of the loop, 7DH is added to AL with CF = 0 and AH = 00. CX = 04 and ZF = 0. In the second iteration of the loop, EBH is added to AL, which results in AL = 68H 1. Since a carry occurred, AH is incremented. CX = 03 and ZF = In the third iteration, CSH is added fo AL, which makes AL =2DH. Again a carry occurred, so AH is incremented again. CX = 02 and ZF = 0. ‘This process continues until CX = 00 and the zero flag becomes 1, which will cause JNZ to fall through. Then the result will be saved in the word-sized memory set aside in the data segment. Although this program works correctly, due to pipelining itis strongly recommended thatthe following lines of the program be replaced: Replace these lines. With these tines. BACK: ADD AL|Si] BACK: ADD ALISI) JNG OVER ADC AH,00 ;add 1 to AH if CF=1 INC AH INC SI OVER: INC SI CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONSThe "ADC AH,00" instruction in reality means add 00 + AH + CF and place the result in AH. This is much more efficient since the instruction "JNC OVER" thas to empty the queue of pipelined instructions and fetch the instructions from the OVER target every time the carry is zero (CF = 0). ‘The addition of many word operands works the same way. Register AX (or CX or DX or BX) could be used as the accumulator and BX (or any general-purpose 16-bit register) for keeping the carrics. Program 3-1b is the same as Program 3-1a, rewritten for word addition. ‘Write a program to calcula is as follows: 27345, 28521, 29533, 30105, and 32375, the total sum of five words of data. Fach data value represents the yearly wages of a worker. This person does not make more than $65,555 (FFFFH) a year. The decimal data TITLE PROG3-1B (EXE) ADDING S WORDS PAGE 60,132 MODEL SMALL STACK 64 DATA COUNT QU. 05 DATA OW 27345,28521,29533,30105,32375 ORG —Oo10H suM = BW. 2DUP(7) ‘CODE MAIN PROC’ FAR MOV AX@DATA MOV DS.AK MOV CX {OX Is the oop counter MOV _SI,OFFSET DATA\SI's the data pomnter Mov AX00 'AX will hold te sum MOV BXAX {BK wal hold the carries BACK: ADD AX|SI] add the next word to AX ADC BXO Jadd carry to BX inc si lincrement data pointer twice INC 8I ‘to point to next word DEC Cx ‘decrement loop counter WZ BACK ‘iat fishes, continue adding MOV SUMAX ;Store the sum MOV SUM*2.BX “stove the cartes MoV AHACH INT 2H go back to 008 MAN ENOP END MAIN Program 3-1b CASE 2: Addition of multiword numbers Assume a program is needed that will add the total U. S. budget for the last 100 ycars or the mass of all the planets in the solar system. In cases like this, the numbers being added could be up to 8 bytes wide or more, Since registers are only 16 bits wide (2 bytes), it is the job of the programmer to write the code to break down these large numbers into smaller chunks to be processed by the CPU. Ifa 16-bit register isused and the operand is 8 bytes wide, that would take a total of four iterations. However, if an 8-bit register is used, the same operands would require cight iterations. This obviously takes more time for the CPU. This is onc reason to have wide registers in the design of the CPU. Large and powerful computers such as the CRAY have registers of 64 bits wide and larger. SECTION 3.1: UNSIGNED ADDITION AND SUBTRACTION 85Write a program that adds the following two multiword numbers and saves the result: DATAI = $48FB9963CE7H and DATA2 = 3FCD4FA23B8DH. TITLE PROG3-2 (EXE) MULTIWORD ADDITION PAGE _ 60,132 MODEL SMALL STACK 64 DATA DATA1 DQ. S4eFE9963CE7H ORG 0010H DATA2 BQ. 3FCD4FAZSBBDH ORG 902011 DATAS «DQ 2 MAIN clear carry before fist adeltion MOV Si,OFFSETOATAL ‘Slis ponter for operandt MOV DIOFFSETDATA2 ——_Dlis pointer for operand? MOV BXOFFSETDATAS —_[SXie pointer forthe sum MOV CX 04 'oX's the loop counter BACK) «= MOV AXIS! ‘rove the frst operand to AX ADS AXIO! ‘ad the second operand to AX Mov (Bx) ‘Store te sum INC &I point fo next word of operand ING SI INC DI point to next word of operand2 INC DI INC Bx ‘point to next word of sum INC. Bx Loop BACK ‘ifnot finished, continue adding MOV AH.AGH INT 21H :90 back to 008 MAIN ENOP: END MAIN Program 3-2 Analysis of Program 3-2 In writing this program, the first thing to be decided was the directive used for coding the data in the data segment. DQ was chosen since it can represent data as large as 8 bytes wide. The question is: Which add instruction should be used? In the addition of multibyte (or multiword) numbers, the ADC instruction is always used since the carry must be added to the next-higher byte (or word) in the next iteration, Before executing ADC, the carry flag must be cleared (CF = 0) so that in the first iteration, the carry would not be added. Clearing the carry flag is achieved by the CLC (clear carry) instruction. Three pointers have been used: SI for DATA, DI for DATA2, and BX for DATA3 where the result is saved. There is a new instruction in that program, "LOOP XXXX", which replaces the often used "DEC CX" and "INZ_XXXX". In other words: LOOP 2.00 is equivalent to the following two instructions. DEC Cx JNZ 00 When the "LOOP xxxx" is executed, CX is decremented automatically, and if CX is not 0, the microprocessor will jump to target address xxx. If CX is 0, the next instruction (the one below "LOOP 0x") is executed CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONS‘Subtraction of unsigned numbers SUB dest,source :dest = dest - source In subtraction, the 80x86 microprocessors (indeed, almost all modem CPUs) use the 2’s complement method. Although every CPU contains adder circuitry, it would be too cumbersome (and take too many transistors) to design separate subtractor circuitry. For this reason, the 80x86 uses internal adder circuitry to perform the subtraction command, Assuming that the 80x86 is executing simple subtract instructions, one can summarize the steps of the hardware of the CPU in executing the SUB instruction for unsigned numbers, as follows, 1. Take the 2's complement of the subtrahend (source operand), 2, Add it to the minuend (destination operand). 3. Invert the carry These three steps are performed for every SUB instruction by the internal hardware of the 80x86 CPU regardless of the source and destination of the operands as long as the addressing mode is supported. It is after these three steps that the result is obtained and the flags are set. Example 3-2 illustrates the three steps, Example Show the st involved in the followin; Mov AL3H toad AL=3F mov BH 23H ‘oad BH=23 SUB ALBH ‘subtract BH from AL. Place result in AL Solution: AL oF gost aint oot sin4 BA -23 -0010 0011 +1101 1101 (2's complement) ic T0001 7100 CF=0 (step 3) The flags would be set as follows: CF = 0, ZF = 0, AF = 0, PF = 0, and SF = 0, The programmer must ook at the carry flag (not the sign flag) to determine if the result is positive or negative. ‘After the execution of SUB, if CF = 0, the result is positive; if CF = 1, the result is negative and the destination has the 2's complement of the result. Normally, the result is left in 2°s complement, but the NOT and INC instructions can be used to change it, The NOT instruction performs the 1s complement of the operand; then the operand is incremented to get the 2’s complement, See Example 3-3. Example ‘Analyze the following program: irom the date segment: DATA! DB CH DATA2 DB GEH DATAS DB? ‘rom the code segment MOV" OH.OATA1 ——_;joad DH with DATA value (4CH) SUB DH'DATA2 —_—_ subtract DATA2 (6E) from DH (4CH) JNC NEXT 5H CF=0 jump to NEXT target NoT OH ‘it CF=1 then take 1's complement INC OH Jand inerement to get 2's complement NEXT. MOV DATA3.0H_~—_ save DHin DATAS. Solution: Following the three steps for "SUB DH,DATA2" 4C "0100 1100 0100 1100 =8E 01101110 2s comp +1001 0010 -2 O1101 1110 _CF=1 (step 3) the result is negative SECTION 3.1: UNSIGNED ADDITION AND SUBTRACTION 87‘SBB (subtract with borrow) This instruction is used for multibyte (multiword) numbers and will take care of the borrow of the lower operand. If the carry flag is 0, SBB works like SUB. Ifthe carry flag is 1, SBB subtracts | from the result. Notice the "PTR" operand in Example 3-4, The PTR (pointer) data specifier directive is widely used to specify the size of the operand when it differs from the defined size. In Example 3-4, "WORD PTR" tells the assembler to use a word operand, even though the data is defined as a doubleword. Example 3-4 ‘Analyze the following program: DATAA RESULT Solution: After the SUB, AX = 62FA - 963B = CBF and the carry flag is set. Since CF = 1, when SBB is executed, AX = 625—412~1=212. Therefore, the value stored in RESULT is 0212CCBF. DD 62562FAH DD 412963BH DD? Wov" AX,WORD PTR DATA A TAXE62FA SUB AX WORD PTR DATA 8 SUB 968 from AX MOV WORD PTR RESULTAX ‘save the result MOV AXWORD PTR DATA A+2 (AX=0625 SBB AX WORD PTR DATA “8 +2 (SUB 0412 with borrow MOV WORD PTR RESULT#2,AX ‘save the result Review Questions 1. The ADD instruction that has the syntax "ADD destination, source” replaces the operand with the sum of the two operands. 2. Why/is the following ADD instruction illegal? ADD DATA_1,DATA_2 3. Rewrite the instruction above in a correct form. 4. The ADC instruction that has the syntax "ADC destination, source” replaces the ‘operand with the sum of. . 5. The execution of part (a) below results in ZF = I, whereas the execution of part (b) results in ZF = 0. Explain why. (a) MOV BL,04FH (b) MOV BX,04FH ADD BL.OBIH ADD BX,0BIH ‘The instruction "LOOP ADD_LOOP" is equivalent to what two instructions? Show how the CPU would subtract OSH from 43H. IfCF = 1, AL = 95, and BL = 4F prior to the exccution of "SBB AL,BL", what will be the contents of AL after the subtraction? SECTION 3.2: UNSIGNED MULTIPLICATION AND DIVISION ‘One of the major changes from the 8080/85 microprocessor to the 8086 was inclusion of instructions for multiplication and division. In this section we cover each one with examples. This is multiplication and division of unsigned numbers. Signed numbers are treated in Chapter 6. In multiplying or dividing two numbers in the 80x86 microprocessor, the use of registers AX, AL, AH, and DX is necessary since these functions assume the use of those registers. Multiplication of unsigned numbers In discussing multiplication, the following cases will be examined: (1) byte times byte, (2) word times word, and (3) byte times word. CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONSbyte x byte: In byte by byte multiplication, one of the operands must be in the AL register and the second operand can be either in a register or in memory as addressed by one of the addressing modes discussed in Chapter 1. After the multiplication, the result is in AX. See the following example: RESULT OW ? :resull is defined in the data segment MOV AL,25H sa byte is moved to AL MOV BL.65H immediate data must be in a register MUL BL ‘AL = 25 x 65H MOV RESULTAX the resultis saved In the program above, 25H is multiplied by 65H and the result is saved in word-sized memory named RESULT. In that example, the register addressing mode ‘was used, The next three examples show the register, direct, and register indirect addressing modes. jfrom the data segment: DATA = OB 25H DATA2 OB 65H RESULT DW ? sfrom the code segment: MOV AL.DATAt MOV BL,DATA2 MUL BL sregister addressing mode MOV RESULTAX or MOV AL,DATA1 MUL DATAZ ‘direct addressing mode MOV RESULTAX or MOV AL.DATA1 MOV SI,OFFSET DATA2 MUL BYTE PTRISI] stegister indirect addressing mode MOV RESULTAX In the register addressing mode example, any 8-bit register could have been used in place of BL. Similarly, in the register indirect example, BX or DI could have been used as pointers. If the register indirect addressing mode is used, the operand size must be specified with the help of the PTR pseudo-instruetion. In the absence of the "BYTE PTR" directive in the example above, the assembler could not figure out if it should use a byte or word operand pointed at by SI. This confusion would cause an error, word x word: In word by word multiplication, one operand must be in AX and the second operand can be in a register or memory. After the multiplication, registers AX and DX will contain the result. Since word x word multiplication can produce a 32-bit result, AX will hold the lower word and DX the higher word. Example: DATA3 DW = 2378H DATAS DW 2F7H RESULT1 = DW 2 DUP(?) MOV AX,DATA3 :Joad first operand into AX MUL DATA :mutiply it by the second operand MOV RESULT1,AX :slore the lower word result MOV RESULT1+2.DX :store the higher word result SECTION 3.2: UNSIGNED MULTIPLICATION AND DIVISION 89word x byte: This is similar to word by word multiplication except that AL contains the byte operand and AH must be set to zero. Example: sfrom the data segment: DATAS DB 6BH DATA DW = 12C3H RESULT3 = DW 2:DUP(?) sfrom the code segment: MOV’ AL,DATAS ‘AL holds byte operand SUB AH,AH ‘AH must be cleared MUL DATAG ‘byte in AL multiplied by word operand MOV BX,OFFSET RESULTS ‘BX points to storage for product MOV [BX],AX iAX holds lower word Mov [BX]+2,Dx DX holds higher word Table 3-1 gives a summary of multiplication of unsigned numbers. Using the 80x86 microprocessor to perform multiplication of operands larger than 16-bit size takes some manipulation, although in such cases the 8087 coprocessor is normally used. Table 3-1: Unsigned Multiplication Summary ce Multiplication _|Operand 1 Operand 2 [Reson | byte x byte AL register or_memory AX | jword x word AX __register or memory _Dxax | wordx byte __AL=byte, AH register or memory _ ‘DXAX Division of unsigned numbers In the division of unsigned numbers, the following cases are discussed: 1. Byte over byte 2. Word over word 3. Word over byte 4. Doubleword over word In divide, there could be cases where the CPU cannot perform the division. In these cases an interrupt is activated. In recent years this is referred to as an exception. In what situation can the microprocessor not handle the division and must call an interrupt? They are 1. if the denominator is zero (dividing any number by 00), and 2. if the quotient is too large for the assigned register. In the IBM PC and compatibles, if cither of these cases happens, the PC will display the "divide error” message byte/byte: In dividing a byte by a byte, the numerator must be in the AL register and AH must be set to zero. The denominator cannot be immediate but can be in a register or memory as supported by the addressing modes. After the DIV instruction is performed, the quotient is in AL and the remainder is in AH. The following shows the various addressing modes that the denominator can take. 90 CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONSDATA? DB 95 DATAS = OB 10 QOuT1 DB 7 REMAIN1 DB 2 iusing immediate addressing mode will give an error Mov ‘AL,DATA7 move data into AL ‘SUB AH.AH :olear AH piv 10 ‘immed. mode not allowed! allowable modes include: ‘using direct mode Mov ALDATAT {AL holds numerator SUB AHAH jAH must be cleared bv DATAB idivide AX by DATAS Mov QOUT1,AL — jquotient = AL = 09 Mov REMAIN1,AH remainder = AH = 05 jusing register addressing mode MOV AL,DATAT —_;AL holds numerator SUB ‘AH/AH "AH must be cleared MOV —-BH,DATAB move denom. to register pV BH ‘divide AX by BH MOV QOUT1.AL___ quotient = AL = 09 MOV REMAIN,AH remainder = Al ‘using register indirect addressing mode MOV ALDATA7 ‘AL holds numerator SUB AHAH {AH must be cleared MOV BX.OFFSETDATA8 —_ 8X holds offset of DATAS ov BYTE PTR [BX] ‘divide AX by DATAB Mov QOUT2,AX MOV REMAIND2,0x word/word: In this case the numerator is in AX and DX must be cleared The denominator can be in a register or memory. After the DIV, AX will have the quotient and the remainder will be in DX. Mov AX,10050 |X holds numerator SUB Dx,0x :DX must be cleared Mov BX, 100 BX used for denominator ov Bx Mov QOUT2,AX quotient = AX = 64H = 100 Mov REMAIND2,0X jremainder = DX = 32H = 50 word/byte: Again, the numerator is in AX and the denominator can be in aregister or memory. After the DIV instruction, AL will contain the quotient, and ‘AH will contain the remainder. ‘The maximum quotient is FFH. The following program divides AX = 2055 by CL=100. Then AL= 14H (20 decimal) isthe quotient and AH = 37H (55 decimal) is the remainder, MOV AX,2055 JAX holds numerator MOV 1,100 :CL used for denominator ov cL MOV QUO,AL :AL holds quotient Mov REMIAH :AH holds remainder SECTION 3.2: UNSIGNED MULTIPLICATION AND DIVISION 1doubleword/word: ‘The numerator is in AX and DX, with the most significant word in DX and the least significant word in AX. The denominator can be in a register or in memory. After the DIV instruction, the quotient will be in AX, the remainder in DX. The maximum quotient is FFFFH sfrom the data segment: DATA 0D 105432 DATA2 = OW 10000 QuoT = OW 2 REMAIN OW 2 sfrom the code segment: MOV AX.\WORD PTR DATAt {AX holds lower word MOV DX.WORDPTRDATA1+2 ——_:DX higher word of numerator Div DATA2 MOV QUOT,AX ‘AX holds quotient MOV REMAIN.OX :DX holds remainder In the program above, the contents of DX:AX are divided by a word-sized data value, 10000. Now one might ask: How does the CPU know that it must use the doubleword in DX:AX for the numerator? The 8086/88 automatically uses DX:AX as the numerator anytime the denominator is a word in size, as was seen earlier in the case of a word divided by a word. This explains why DX had to be cleared in that case. Notice in the example above that DATAL is defined as DD but fetched into a word-size register with the help of WORD PTR. In the absence of WORD PTR, the assembler will generate an error. A summary of the results of division of unsigned numbers is given in Table 3-2. je 3-2: Unsigned Division Summary Division Numerator Denominator Quotient (Rem lnytebyte AL =byte, AH=0 —_registerormemory AL! jan word/word ___—-|AX= word, DX=0_register or memory jax? DX word/byte AX = word register or memory __AL! AH | (doubleword/word _DXAX=doubleword __register or memory Ax? Dx ines {Divide ero interrupt if AL > FFH, 2 Divide errr tert f AX. >FFFFH, Review Questions 1. Inunsigned multiplication of a byte in DATA with a byte in AL, the product will be placed in register(s) 2. Inunsigned multiplication of AX with BX, the product is placed in register(s) In unsigned multiplication of CX with a byte in AL, the product is placed in regis- a 4, Inunsigned division ofa byte in AL by a byte in DH, the quotient will be placed in and the remainder in In unsigned division of a word in AX by a word in DATAL, the quotient will be placed in and the remainder in In unsigned division of a word in AX by a byte in DATA2, the quotient will be placed in __andthe remainder in 7. In unsigned division of a doubleword in DXAX by a word in CX, the quotient will be placed in and the remainder in a 92 CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONS.SECTION 3.3: LOGIC INSTRUCTIONS AND SAMPLE PROGRAMS In this section we discuss the logic instructions AND, OR, XOR, SHIFT, and COMPARE. Instructions are given in the context of examples, AND AND destination, source This instruction will perform a logical AND on the operands and place the result in the destination, The destination operand can be a reg- ister or in memory. The source operand can be a register, in memory, or immediate. Example 3-5 Show the results of the following: Mov BLa5H AND BLOPH {AND BL with OFH. Place the resultin BL Solution: as 00110101 of oooo11 41 CF 90044 OSH ODOOTTOT Flag setings willbe: SF = 0, ZF = 0, P oF <0. AND will automatically change the CF and OF to zero and PF, ZF and SF are set according to the result The rest of the flags are either undecided or unaffected. As seen in Example 3-5, AND can be used to mask certain bits of the operand. It can also be used to test for a zero operand: AND DH,DH JZ XXXK XXXX: The above will AND DH with itself and set ZF = | if the result is zero, making the CPU fetch from the target address XXXX. Otherwise, the instruction below JZ is executed. AND can thus be used to test if a register contains zero. OR OR — destination,source The destination and source operands are ORed and the result is placed in the destination. OR can be used to set certain bits of an operand to 1. The destination operand can be a register or in memory. The source operand can be a register, in memory, or immediate. The flags will be set the same as for the AND instruction. CF and OF will be reset to zero and SF, ZF, and PF will be set according to the result. All other flags are not affected. See Example 3-6 The OR instruction can also be used to test for aero operand. For example, “OR BL,O" will OR the register BL with 0 and make ZF = 1 if BL is zero, "OR BL,BL" will achieve the same result, SECTION 3.3: LOGIC INSTRUCTIONS AND SAMPLE PROGRAMS . 93Example 3-6 Show the results of the following: MOV Ax.0504 AX = 0508 OR AX,0DA68H "AX = DF6C Solution: (95044 0000 0101 0000 0100 tf 5 e1,2F=0,PE=1,cF0F=0 DASH 1101 101 lags willbe: SF =1 , ZF = 0, PF = 1, CF = OF = Bree, Horisitoro Teo. Notice that party is checked for the lower 8 bits only. XOR XOR dest.src ‘The XOR instruction will eXclusive-OR the operands and place the result in the destination, XOR sets the result bits to 1 if they are not equal; otherwise, they are reset to 0. The Nags are set the same as for the AND instruction. CF = 0 and OF = 0 are sct internally and the rest are changed according to the result of the operation. The rules for the operands are the same as in the AND and OR instructions. See Examples 3-7 and 3-8. Example 3-7 Show the results of the following: MOV _DH.S4H XOR —_-DH,78H_ Solution: SiH 78H 2c Flag settings will be: SF = 0, ZF = 0, PF =0, CF = OF =0 Example 3-8 The XOR instruction can be used to clear the contents of a register by XORing it with itself. Show how "XOR AH,AH" clears AH, assuming that AH = 45H. Solution: aH 91900101 45H on 8 600003 Fag soting wil be: SF =0, ZF = 1, PF=1 OF = OF <0 XOR can also be used to see if two registers have the same value. "XOR BX,CX" will make ZF = | if both registers have the same value, and if they do, the result (0000) is saved in BX, the destination, Another widely used application of XOR is to toggle bits of an operand. For example, to toggle bit 2 of register AL: XOR AL,O4H :XOR AL with 0000 0100 This would cause bit 2 of AL to change to the opposite value; all other bits ‘would remain unchanged 94 CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONSSHIFT ‘There are two kinds of shift: logical and arithmetic. The logical shift is for unsigned operands, and the arithmetic shift is for signed operands. Logical shift will be discussed in this section and the discussion of arithmetic shift is postponed to Chapter 6. Using shift instructions shifts the contents of a register or memory location right or left. The number of times (or bits) that the operand is shifted can be specified directly if it is once only, or through the CL register if it is more than once SHR: This is the logical shift right. ° The operand is shifted right bit by bit, and for every shift the LSB (least significant bit) will go to the carry flag (CF) and the MSB. (most significant bit) is filled with 0. Examples 3-9 and 3-10 should help to clarify use| —— cr IMse SHR. Example 3-9 Show the result of SHR in the following: MOV ALOAH MOV CL.3.:setnumber of times to shit SHR ALICL Solution: 9AH = 10011010 or00r10% (shifted once) go100110 (hited twice) 00010014 (ehitted three times) After three times of shifting right, AL = 13H and CF = 0. If the operand is to be shifted once only, this is specified in the SHR instruction itself rather than placing I in the CL. This saves coding of one instruction; MOV BX,OFFFFH (BX=FFFFH SHR 8X1 ‘shift right BX once only ‘After the shift above, BX = 7FFFH and CF = I. Although SHR does affect the OF, SF, PF, and ZF flags, they are not important in this case. The operand to be shifted can be in a register or in memory, but immediate addressing mode is not allowed for shift instructions. For example, "SHR 25,CL" will cause the assembler to give an error. Example 3-10 Show the results of SHR in the following: ‘from the data sogment: DATAL OW 7777H from the code segment: TIMES EQU 4 MOV” CL,TIMES cL=04 SHR DATAI,CL ‘shit DATA CL times Solution: After the four shifts, the word at memory location DATAL will contain 0777. The four LSBs are lost through the carry, one by one, and 0s fill the four MSBs, SECTION 3.3: LOGIC INSTRUCTIONS AND SAMPLE PROGRAMS, 95SHL: Shift left is also a logical shift. It is the reverse of SHR. After every shift, the LSB is filled with OF MSB LsB]—0o 0 and the MSB goes to CF. All the rules are the same as {shifted left once) SHR. Example Show the effects of SHL in the following: Mov DHS Mov CL.4 SHL DK.CL Solution: 00000110 0001100 00011000 00110000 CF=0 01100000 ( After the four shifts left, the DH register has 60H and CF = 0, shifted four times) Example 3-1 could have been coded as MOV 0H6 SHL Ht SHL DH SHL DH,1 SHL OHA COMPARE of unsigned numbers CMP — destination,source compare dest and src ‘The CMP instruction compares two operands and changes the flags accord- ing to the result of the comparison. ‘The operands themselves remain unchanged ‘The destination operand can be in a register or in memory and the source operand can be in a register, in memory, or immediate, Although all the CF, AF, SF, PF, ZF, and OF flags reflect the result of the comparison, only the CF and ZF are used, as outlined in Table 3-3, mpare operands | destination > sourc lag Settings for Compare Instruction The following demonstrates how the CMP instruction is used: DATAt Dw Mov MP JNC sus OVER: INC 236FH ‘AX,OCCCCH AXDATAT — compare CCCC with 235F OVER jump if CF=0 AXAX DATAt 96 CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONSIn the program above, AX is greater than the contents of memory location DATAI (OCCCCH >235FH); therefore, CF = 0 and INC (jump no carry) will go to target OVER. In contrast, look at the following Mov BX,7688H Mov CX.9FFFH CMP BX,CX scompare 7888 with 9FFF JNC NEXT ADD BX,4000H NEXT: ADD CX,250H In the above, BX is smaller than CX (7888H <9FFFH), which sets CF = 1, making "JNC NEXT" fall through so that "ADD BX,4000H" is executed. In the example above, CX and BX still have their original values (CX = 9FFFH and BX = 7888I1) after the execution of "CMP BX,CX". Notice that CF is always checked for cases of greater or smaller than, but for equal, ZF must be used. The next program sample has a variable named TEMP, which is being checked to see if it has reached 99: TEMP DB? MOV AL,TEMP move the TEMP variable into AL cmp AL99 compare AL with 99 Zz HOT_HOT if 2F=1 (TEMP = 99) jump to HOT_HOT INC Bx ‘otherwise (ZF=0) increment BX HOT_HOT: HLT shalt the system ‘The compare instruction is really a SUBtraction except that the values of the operands do not change. The flags are changed according to the execution of SUB. Although all the flags are affected, the only ones of interest are ZF and CF. It must be emphasized that in CMP instructions, the operands are unaffected regardless of the result of the comparison. Only the flags are affected. This is despite the fact that CMP uses the SUB operation to set ot reset the flags. Program 3-3 uses the CMP instruction to search for the highest byte in a series of 5 bytes defined in the data segment. The instruction "CMP AL,[BX]" works as follows, where [BX] is the contents of the memory location pointed at by register BX. If AL < [BX], then CF = | and [BX] becomes the basis of the new comparison. If AL > [BX], then CF = 0 and AL is the larger of the two values and remains the basis of comparison. Although JC Gump carry) and JNC (jump no carry) check the carry flag and ‘can be used after a compare instruction, it is recommended that JA (jump above) and JB (jump below) be used for two reasons. One reason is that DEBUG will unassemble JC as JB, and JNC as JA, which may be confusing to beginning programmers, Another reason is that "jump above" and "jump below” are easier to understand than "jump carry" and "jump no carry," since it is more immediatcly apparent that one number is larger than another, than whether a carry would be ‘generated if the two numbers were subtracted. Program 3-3 uses the CMP instruction to search through 5 bytes of data to find the highest grade. The program uses register AL to hold the highest grade found so far. AL is given the initial value of 0. A loop is used to compare each of the 5 bytes with the value in AL. If AL contains a higher value, the loop continues to check the next byte. If AL is smaller than the byte being checked, the contents of AL are replaced by that byte and the loop continues, SECTION 3.3: LOGIC INSTRUCTIONS AND SAMPLE PROGRAMS:Assume that there is a class of five people the following grades: 69, 87, 96, 45, and 75 Find the highest grade. TIME — PROGS-3 (EXE) CMP EXAMPLE PAGE 60.132 MODEL SMALL STACK 64 . DATA GRADES DB 69,87,00.45,75 ORG 9008 HIGHEST 08? : ‘CODE MAIN PROC FAR, MOV" AXQDATA Os) MOV MOV OX :Set up loop counter MOV BXOFFSET GRADES ‘BX points o GRADE data, SUB ALAL {AL holds highest grade found so far AGAIN: GMP ALEX) highest JA NEXT imp f AL stil highest MOV AL[BX) ise AL holds new highest Next INC BX ‘point to next grade LOOP AGAIN ‘Continue search MOV HIGHESTAL ‘store highest grade MOV AH.ACH INT 21H :go back to DOS MAIN ENDP END MAIN Program 3-3 Program 3-4 uses the CMP instruction to determine if an ASCII character is uppercase or lowercase. Note that small and capital letters in ASCII have the following values: [Letter _| Hex | Binary Letter | Hex | Binary | A 41_| 01000001 a__| 61 | o100001 B 42 | o1ooooi0 | _b | 62_| o1ooo10 c 43__| 0100001 63_| ono0011 Y $9_| 01011001 y , 79 | o1tt091 _ | Zz SA_|_o1on0i0 z_| 7A | _o1nioi0 As-can be seen, there is a relationship between the pattem of lowercase and uppercase letters, as shown below for A and a: ‘A 01000001 41H a 01100001 61H ‘The only bit that changes is dS, To change from lowercase to uppercase, d5 must be masked. Program 3-4 first detects if the letter is in lowercase, and if it is, it is ANDed with 1101 1111B = DFH. Otherwise, itis simply left alone. To determine if itis a lowercase letter, itis compared with 61H and 7AH to see if itis in the range ato z, Anything above or below this range should be left alone. 98 (CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONS,TITLE PROGS-4 (EXE) LOWERCASE TO UPPERCASE CONVERSION PAGE 60,192 MODEL SMALL STACK 64 ATA DATAT DB “mY NAME is jOe ORG —0020H DaTa2 DB 14DUP(?) ‘CODE MAIN PROG FAR MOV AX@DATA Mov DS.AX MOV SLOFFSET DATA! —_—_;SI points to original data MOV BX.OFFSETOATA2 “BX points to uppercase data Mov cx.14 CX 's loop counter Back «= MOV ALIS!) get next character CMP ALGIH ‘less than a WB OVER then no need to convert CMP ALTA it greater than vA OVER ‘then no need to convert AND AL,110111118 “mask dS to convert to uppercase OVER, = MOV [BXIAL ‘store uppercase character INC SI increment pointer to original INC Bx increment pointer to uppercase data LooP BACK ‘continue looping if CX > 0 MOV AHACH INT 21H :0 back to DOS MAIN. ENDP ENO MAIN Program 3-4 In Program 3-4, 20H could have been subtracted from the lowercase letters instead of ANDing with 1101 1111B. That is what IBM does, as shown next. IBM BIOS method of converting from lowercase to uppercase 2387 ‘— CONVERT ANY LOWERCASE TO UPPERCASE 2358 EBFB 2359 Keo: {LOWER TO UPPER EBFB 3061 2360 cMP AL; "FIND OUT IF ALPHABETIC EBFD 7208 2361 JB St INOT_CAPS_STATE EBFFSC7A 2362 cup ALZ C01 7702 2363 Ja K6t :NOT_CAPS_STATE C03 202 2364 SUB AL‘aA [CONVERT TO UPPERCASE COS 2365 Ket COS 8B1E1C00 2366 MOV BK.BUFFER_TAIL {GET THE END POINTER STO THE BUFFER (Reprinted by permission from “IBM Technical Reference” c, 1984 by international Business Machines Corporation) a wae Review Questions Use operands 4FCAH and C237H to perform: (a) AND (b) OR (c) XOR ANDing a word operand with FFFFH will result in what value for the word oper- and? To set all bts of an operand to 0, it should be ANDed with To set all bits of an operand to 1, it could be ORed with XORing an operand with itself results in what value for the operand? ‘Show the steps if value AOF2H were shifted left three times, Then show the steps if AOF2H were shifted right threc times. ‘The CMP instructions works by performing a(n) operation on the oper ands and setting the flags accordingly. True or false. The CMP instruction alters the contents of its operands. SECTION 3,3: LOGIC INSTRUCTIONS AND SAMPLE PROGRAMSE058 E056 E088 OSE FA EOSC B45 EOSE 9& E05F 7340 E061 7544 E063 7848 £065 7946 067 9F £068 B105 E06A O2EC E06C 733F EO8E 8040 070 DEO 0727139 E074 3264 076 9E 077 7634 079 132 078 730 07D 9F EO7E B105 080 D2EC. 082 7229 £084 DOES £086 7025 £088 BEFFFF E08B F9 E08c E08C sED8 E08E 8CDB £090 8EC3 £092 8CC1 £094 BED) E096 acb2 £098 BEEZ E09A 8BEC. E09C 8BF5 EO9E BFE EOAQ 7307 E0A2 33C7 EOA4 7507 EOA6 Fa E0A7 EBE3 EOAa E0A9 oBC7 EOAB 7401 EOAD Fa BIOS examples of logic instructions In this section we examine some real-life examples from IBM PC BIOS programs. The purpose is to see the instructions discussed so fa real-life applications. When the computer is tumed on, the CPU starts to execute the programs stored in BIOS in order to set the computer up for DOS. Ifanything has happened to the BIOS programs, the computer can do nothing, The first subroutine of BIOS, is to test the CPU. This involves checking the flag register bit by bit as well as checking all other registers. The BIOS program for testing the flags and registers is given followed by their explanation: the context of 306 ASSUME CS:CODE,DS!NOTHING ES NOTHING SS:NOTHING 307 ORG OEOSBH 309 START: 310 cu ; DISABLE INTERRUPTS an MOV AH.ODSH SET SF, CF, ZF, AND AF FLAGS ON 312 SAHF 313 NC ERROT GO TO ERR ROUTINE IF CF NOT SET 314 NZ ERROW [GO TO ERR ROUTINE IF ZF NOT SET 315, NB ERROW [GOTO ERR ROUTINE IF PF NOT SET 316 UNS ERRO1 [GOTO ERR ROUTINE IF SF NOT SET 317 LAHF ; LOAD FLAG IMAGE TO AH, 318 MOV CLS LOAD CNT REG WITH SHIFT CNT 319 SHR AH.CL | SHIFT AF INTO CARRY BIT POS, 320 NC ERROt }GO TO ERR ROUTINE IF AF NOT SET 321 Mov ALAOH } SET THE OF FLAG ON 322 SHL ALT } SETUP FOR TESTING 323 JNO ERROW £GO TO ERR ROUTINE IF OF NOT SET 324 XOR_ AHAH ISETAH=0 225 SAHE CLEAR SF. CF ZF, AND PF 326 BE ERROI :GO TO ERR ROUTINE IF CF ON 327 £OR GO TO ERR ROUTINE IF ZF ON JS ERROT {GOTO ERR ROUTINE IF SF ON JP ERROt }GO TO ERR ROUTINE IF PF ON LaHF :LOAD FLAG IMAGE TO AH, MOV CLS } LOAD CNT REG WITH SHIFT CNT SHR AH.CL ‘SHIFT “AF' INTO CARRY BIT POS. JG” ERROI 30 TO ERR ROUTINE IF ON SHL AH [CHECK THAT OF 'IS CLEAR JO” ERROI $GO TO ERR ROUTINE IF ON READIWRITE THE 888 GENERAL AND SEGMENTATION REGISTERS. WITH ALL ONES AND ZEROES, 340 MOV AXOFFFFH — ; SETUP ONE'S PATTERN INAX 31 STC 342.08: 343 MOV DS,AX WRITE PATTERN TO ALL REGS 344 MOV 8XDS 345, MOV ES|BX 346 Mov CXES 347 Mov SS,cx 348 Mov Dx'ss. 349 Mov SPDx 350 Mov BPSP 351 Mov S1.BP 352 Mov D1Si 353 INC C9) STSTIA 354 XOR AXOI | PATTERN MAKE IT THRU ALL REGS 355 JNZ RRO‘ iNO - GO TO ERR ROUTINE 358 cic 357 iMP cB 358 C9: 359 OR = AXDI 3 ZERO PATTERN MAKE IT THRU? 360 wz cto !YES - GOTO NEXT TEST 361 ERROM: HLT [HALT SYSTEM (Reprinted by permission from “IBM Technical Reference" c. 1984 by International Business Machines Corporation) 100 CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONSLine 310 31 312 313-316 317 318 319 320 321-323 324-335 340 341 343 - 352 353 354 355 356 357 359 360 Line-by-line explanation: Explanation CLT ensures that no interrupt will occur while the test is being conducted, MOV AH,ODSH: flag SZ-aAC-P-C DH 1101 010: SAHE (store AH into lower byte of the flag register) is one way to move data to flags, Another is to use the stack MOV ‘AX.00D5H PUSH AX POPF However, there is no RAM available yet to use for the stack because the CPU is tested before memory is tested. Will make the CPU jump to HLT if any flag does not work. LAHF (load AH with the lower byte of flag register) is the opposite of SAHF. Loads CL for five shifts. "SHR AH,CL". By shifting AH five times, AF (auxiliary carry) will be in the CF position. Ifno AF, there is an error. Lines 317 to 320 are needed because there is no jump condition instruction for AF. Checks the OF flag. This is discussed in Chapter 6 when signed numbers are discussed. Checks the same flags for zero. Remember that JNZ is the same as JBE. Loads AX with FFFFH. STC (set the carry) makes CF = 1 Moves the AX value (FFFFH) into every regi registers are good. Since CF=1 (remember STC) it falls through, Exclusive-ORing AX and DI with both having the same FFFFH value makes AX = 0000 and ZF = | if the registers are good (see lines 343 - 352), If ZF = 0, one of the registers must have corrupted the data FFFF, therefore the CPU is bad. IFZF ~ 0, there is an error. CLC clears the carry flag. This is the opposite of STC. Jumps to C8 and repeats the same process, this time with value 0000. ‘The contents of AX are moved around to every register until DJ ~ 0000, and at 353 the INC C9 will jump since CF = 0 by the CLC instruction before it went to the loop. ‘AtC9, AX and DI are ORed. 1f 0000, the contents of AX are copied successfully to all registers, DI will be 0000; therefore, ORing will raise the ZF, making ZP = IfZF = 1, the CPU is good and the system can perform the next test. Otherwise, ZF = 0, meaning that the CPU is bad and the system should be halted. fer and ends up with DI = FFFFH if the SECTION 3.4: BCD AND ASCII OPERANDS AND INSTRUCTIONS | Digit BCD In 80x86 microprocessors, there are many in- = structions that handle ASCII and BCD numbers. This ° 0000 ‘section covers these instructions with examples. ; oer 9012 BCD number system ; pena BCD stands for binary coded decimal. BCD is 2 pues needed because human beings use the digits 0 to 9 for 3 Oras numbers, Binary representation of 010 9 iscatled BCD (see, a 1000 Figure 3-1). In computer literature one encounters two 9 1001 terms for BCD numbers = (1) unpacked BCD (2) packed BCD. Figure 3-1. BCD Code SECTION 3.4: BCD AND ASCII OPERANDS AND INSTRUCTIONS, 101Unpacked BCD In unpacked BCD, the lower 4 bits of the number represent the BCD number and the rest of the bits are 0. Example: "0000 1001" and "0000 0101" are unpacked BCD for 9 and 5, respectively. In the case of unpacked BCD it takes 1 byte of memory location or a register of 8 bits to contain it. Packed BCD In the case of packed BCD, a single byte has two BCD numbers in it, one in the lower 4 bits and one in the upper 4 bits. For example, "0101 1001” is packed BCD for 59. Ittakes only | byte of memory to store the packed BCD operands. This is one reason to use packed BCD since it is twice as efficient in storing data. ASCII numbers In ASCII keyboards, when key "0" is activated, for example, "011 0000" (30H) is provided to the computer. In the same way, 31H (011 0001) is provided for key "1", and so on, as shown in the following list Key ASCII (hex) Binary BCD (unpackes) Oe OH Bbo0 000 9000 13 044 0008 090 9003 22 011 0919 00 0010 33 011 001 000 oot? 43 0: 0100 000 0100 5 35 044 0101 000 0101 & 3 oi4on0 9000 0110, ad oom: 9000 0444 & 3 O44 1000, 000 1900 8 3 O14 1001 000 100% It must be noted that although ASCII is standard in the United States (and many other countries), BCD numbers have universal application. Now since the Keyboard and printers and monitors are all in ASCII, hhow does data get converted from ASCII to BCD, and vice versa? These are the Subjects covered next. ASCII to BCD conversion ‘To process data in BCD, first the ASCII data provided by the keyboard must. be converted to BCD. Whether it should be converted to packed or unpacked BCD depends on the instructions to be used. There are instructions that require that data be in unpacked BCD and there are others that must have packed BCD data to work properly. Each is covered separately. ASCII to unpacked BCD conversion To convert ASCH data to BCD, the programmer must get rid of the tagged "O11" in the higher 4 bits of the ASCH. To do that, each ASCII number is ANDed with "0000 1111" (OFH), as shown in the next example. This example is written in three different ways using different addressing modes. The following three pro- grams show three different methods for converting the 10 ASCII digits to unpacked BCD. All use the same data segment: ASC DB "962481273: ORG 00104 UNPACK DB 10 DUP(?) In Program 3-5a, notice that although the data was defined as DB, a byte definition directive, it was accessed in word-sized chunks. This is a workable approach; however, using the PTR directive as shown in Program 3-Sb makes the code more readable for programmers 102 CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONSMov oxs MOV BX OFFSET ASC {BX points to ASCII data MOV DLOFFSETUNPACK I points to unpacked BCD data AGAIN: MOV AXIBX) imave next 2 ASCIl numbers 10 AX AND 'AXOFOFH jemove ASCII 3s MOV [DIlAx ‘slore unpacked BCD ADD DIZ to next unpacked BCD data ADD BX2 ‘Point to next ASCII data Loop AGAIN Program 3-58 Mov oxs {0X is loop counter MoV BXOFFSETASC {Bx points to ASC data MOV DIOFFSETUNPACK [I points to unpacked BCD data AGAIN: MOV AXWORD PTR BX) —_imove next 2 ASCII numbers to AX AND AX OFOFH {remove ASCII3s MOV WORD PTR [DI], AX sstore unpacked BCD ADD DIZ ‘Doint to next unpacked BCD data ADD, BX2 ‘bontto next ASCII Gata Loop AGAIN Program 3-5b In both of the solutions so far, registers BX and DI were used as pointers foran array of data. An array is simply a set of data located in consecutive memory locations. Now one might ask: What happens if there are four, five, or six arrays? How can they all be accessed with only three registers as pointers: BX, DI, and SI? Program 3-Sc shows how this can be done with a single register used as a pointer to access two arrays. However, to do that, the arrays must be of the same size and defined similarly. Mov ox.10 oad the counter SUB BX/BX ‘clear BX AGAIN: MOV ALASCIBX) ‘move to AL. content of mem [BX*ASC] AND ALOFH, ‘mask the upper nibble. MOV — UNPACK(BX|AL ‘move to mem (2X+UNPACK] the AL INC Bx smake the pointer to point at next byte Loop AGAIN ‘oop unti tis finshed Program 3-5e Program 3-Se uses the based addressing mode since BX+ASC is used as a pointer. ASC is the displacement added to BX. Either DI or SI could have been used for this purpose. For word-sized operands, "WORD PTR" would be used since the data is defined as DB. This is shown below. Mov AX.WORD PTR ASCIBX] AND AXOFOFH Mov WORD PTR UNPACKEDIBX),AX ASCIi to packed BCD conversion To convert ASCII to packed BCD, itis first converted to unpacked BCD (to get rid of the 3) and then combined to make packed BCD. For example, for 9 and 5 the keyboard gives 39 and 35, respectively. The goal is to produce 9SH or "1001 0101", which is called packed BCD, as discussed earlier. This process is illustrated in detail below. Key ASCII Unpacked BCD. Packed BCD 4 34 ‘90000100 7 a 00000111 01000111 or 47H SECTION 3.4: BCD AND ASCII OPERANDS AND INSTRUCTIONS 103ORG 0010H VAL_ASC DB ‘47 VAL_BCD DB 2 sfeminder: the DB will put 34 in 0010H location and 37 in 0011H Mov AX.WORD PTR VAL_ASC —_;AH=37,AL=34 AND AX,OFOFH imask 3 to get unpacked BCD XCHG AHL swap AH and AL Mov cls :CL=04 to shift 4 times SHL AH.CL shift left AH to get AH=40H oR ALAH ‘OR them to get packed BCD Mov VAL_BCD,AL save the result After this conversion, the packed BCD numbers are processed and the result will be in packed BCD format, As will be seen later in this section, there are special instructions, such as DAA and DAS, which require that the data be in packed BCD. formand give the result in packed BCD. For the result to be displayed on the monitor or be printed by the printer, it must be in ASCII format. Conversion from packed BCD to ASCII is discussed next, Packed BCD to ASCII conversion To convert packed BCD to ASCII, it must first be converted to unpacked and then the unpacked BCD is tagged with 011 0000 (30H). ‘The fullowing shows the process of converting trom packed BCD to ASCII Packed BCD Unpacked BCD ASCII _ 29H 2H & 09H 32H & 39H 0010 1001 0000 0010 & 0000 1001 011 0010 & 011 1001 \VAL1_BCD DB 29H VAL3-ASC DW? Mov AL,VAL1_BCD Mov AH AL joopy AL to AH. now AH=29,AL=29H AND AX,OFOOFH. mask 9 from AH and 2 from AL Mov cua {CL=04 for shift SHR AH.CL ishift right AH to get unpacked BCD. OR AX,3030H ‘combine with 30 to get ASCII XCHG HAL sswap for ASCII storage convention Mov VAL3_ASCAX store the ASCII BCD addition and subtraction After learning how to convert ASCII to BCD, the application of BCD numbers is the next step, There are two instructions that deal specifically with BCD numbers: DAA and DAS. Each is discussed separately, BCD addition and correction There is a problem with adding BCD numbers, which must be corrected. The problem is that after adding packed BCD numbers, the result is no longer BCD. Look at this example: MOV AL,17H ADD AL,28H Adding them gives 0011 1111B (3FH), which is not BCD! ABCD number can only have digits from 0000 to 1001 (or 0t0 9). In other words, adding two BCD numbers must give a BCD result. The result above should have been 17 + 28 = 45 (0100 0101). To correct this problem, the programmer must add 6 (0110) to the low digit: 104 CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONS3F +06 = 45H. The same problem could have happened in the upper digit (for example, in 52H + 87H = D9H). Again to solve this problem, 6 must be added to the upper digit (D9H +60H =139H), to ensure that the result is BCD (52 + 87 = 139).. This problem is so pervasive that all single-chip CISC microprocessors such as the Intel 80x86 and the Motorola 680x0 have an instruction to deal with it, The RISC processors have eliminated this instruction, DAA The DAA (decimal adjust for addition) instruction in 80x86 microproces- sors is provided exactly for the purpose of correcting the problem associated with BCD addition. DAA will add 6 to the lower nibble or higher nibble if needed; otherwise, it will leave the result alone, The following example will clarify these points: DATA1 DB 47H DATA2 DB 25H DATA3 DB? MOV AL,DATA1 —;AL holds first BCD operand MOV BLDATA2 —:8Lholds second BCD operand ADD ALBL :BCD addition DAA cadjust for BCD addition MOV DATA3,AL —_ store result in correct BCD form ‘After the program is executed, the DATAS field will contain 72H (47 + 25 = 72). Note that DAA works only on AL. In other words, while the source can be ‘an operand of any addressing mode, the destination must be AL in order for DAA to work. It needs to be emphasized that DAA must be used after the addition of BCD operands and that BCD operands can never have any digit greater than 9. In other words, no A - F digit is allowed. It is also important to note that DAA works only after an ADD instruction; it wil! not work after the INC instruction. ‘Summary of DAA action 1. If after an ADD or ADC instruction the lower nibble (4 bits) is greater than 9, or if AF = 1, add 0110 to the lower 4 bits. 2. If the upper nibble is greater than 9, or if CF = 1, add 0110 to the upper nibble. In reality there is no other use for the AF (auxiliary flag) except for BCD addition and correction, For example, adding 29H and 18H will resultin 41H, which is incorrect as far as BCD is concerned. Hex BCD 29 0010 1001 +18 +0001 1000 41 01000001 AF =1 +6 + __0170. because AF = 1 DAAwill add 6 to the lower nibble 47 0100 0111 The final result is BCD. Program 3-6 demonstrates the use of DAA after addition of multibyte packed BCD numbers. BCD subtraction and correction The problem associated with the addition of packed BCD numbers also shows up in subtraction, Again, there is an instruction (DAS) specifically designed to solve the problem. Therefore, when subtracting packed BCD (single-byte or multibyte) operands, the DAS instruction is put after the SUB or SBB instruction. AL must be used as the destination register to make DAS work, SECTION 3.4: BCD AND ASCII OPERANDS AND INSTRUCTIONS 105‘Two sets of ASCII data have come in from the keyboard, Write and run a program to : 1, Convert from ASCII to packed BCD. 2, Add the multibyte packed BCD and save it. 3. Convert the packed BCD result into ASCIL TITLE — PROG3-6 (EXE) ASCII TO BCD CONVERSION AND ADDITION PAGE 60,132 MODE SMALL STACK 64 DATA DATAL_ASC DB “9649147816 ORG 00704 DATAZ ASC DB 0072687108" ORG (0020H DATAZ_BCD OB 5 DUP (2) ORG o028H DATA_BCD OB 5 DUP (2) ORG (0304 DATAS_ADD OB 5 DUP (2) ‘ORG (040H DATAS_ASC DB 10 DUP (7) CODE MAIN PROC FAR MOV’ AX@DATA MOV DS.AX MOV —BX/OFFSET DATAI_ASC. ‘BX points to fst ASCII data MOV — DLOFFSET DATAS_BCD DI points to frst BCO data MOV CX10 MOV CX,10 CALL CONV BCD MOV BX,OFFSET DATA2_ ASC MOV DLOFFSET DATA4_BCD CALL CONV sco CALL BCO_ADD MOV SIOFFSET DATAS_ADD MOV DLOFFSET DATABLASC. (CX holds number bytes to conver: ‘convert ASCII to BCD BX points to second ASCII data Di points to second BCD data ‘CX holds number bytes to convert ‘convert ASCII to BCD ‘add the BCD operands ‘SI points to BCD resutt (DI points to ASCII resutt MOV CX.05 ‘CX holds count for convert CALL CONV_asc {convert result to ASCII MOV AHACH INT 21H ‘go back to DOS MAIN ENDP ETHIS SUBROUTINE CONVERTS ASCII TO PACKED BCD Conv Bcd PROC AGAIN’ “MOV AX,BX] :BX=pointer for ASCII data XCHG AHA AND AXOFOFH mask ASCII 3s PUSH CX ‘save the counter MOV. CL4 ‘shift AH left 4 bits SHE AH.CL ito get ready for packing OR ALAH eombine to: make packed BCD Mov [Di,AL !Di=pointer for BCD data ADD BX2 ‘point to next 2 ASCII bytes INC DI ‘point to next BCD data POP cx $estore loop counter LOOP AGAIN RET CONV_BCD ENDP Program 3-6 (continued on the following page) 106 CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONS"THIS SUBROUTINE ADDS TWO MULTIBYTE PACKED BCD OPERANDS BCD_ADD PROC MOV BX,OFFSET DATA3_BCD {BX=pointer for operand 1 MOV DI,OFFSET DATAS BCD ‘Dispointer for operand 2 MOV SLOFFSET DATAS_ADD ‘Sl=pointer for sum. MOV CX.05 cic BACK = MOV ALIBX}+4 ‘get noxt byte of operand t ADC ALIOI}+4 ‘add next Byte of operand 2 DAA Jeorrect for BCD addition MOV [SI}+4,AL ‘save sum DEC Bx ‘point to next byte of operand 4 DEC Ol point to next byte of operand 2 DEC SI point to next byte of sur LOOP BACK RET 8CD_ADD ENOP “THIS SUBROUTINE CONVERTS FROM PACKED BCD TO ASCII CONV-ASC PROC. AGAIN?) MOV AL{SI) :Sl=pointer for BCD data Mov AHAL ‘duplicate to unpack AND AX,OFOOFH unpack PUSH Cx {save counter MOV CL.04 {shift right 4 bits to unpack SHR AHLCL ‘the upper nibble OR AX/3030H make it ASCIL XCHG AHLAL “swap for ASCII storage convention MOV. [DIJAK store ASCII data INC SI point to next BCD data add D2 point to next ASCII data POP cx restore loop counter LOOP AGAIN2 RET ‘CONV_ASC_ENDP END MAIN Program 3-6 (continued from preceding page) ‘Summary of DAS action 1. Ifafter a SUB or SBB instruction the lower nibble is greater than 9, or if AF = 1, subtract 0110 from the lower 4 bits. 2. Ifthe upper nibble is greater than 9, or CF= 1, subtract 0110 from the upper nibble. Due to the widespread use of BCD numbers, a specific data directive, DT, has been created. DT can be used to represent BCD numbers from 0 to 1070-1 (that is, twenty 93). Assume that the following operands represent the budget, the ‘expenses, and the balance, which is the budget minus the expenses. BUDGET DT _~—-87965141012 EXPENSES DT 31610540392 BALANCE DT =? sbalance = budget - expenses Mov CX,10 jeounter=10 MOV BX,00 ‘pointer=0 cLe jelear carry for the 1st iteration BACK: MOV AL,BYTE PTR BUDGETISX] _ get a byle of the BUDGET SBB AL.BYTE PTR EXPENSES|BX] ;subtract a byte from it DAS correct the resukt for BCD MOV BYTEPTR BALANCE[BX]AL _;save it in BALANCE INC BX sincrement for the next byte LOOP BACK continue until CX=0 SECTION 3.4: BCD AND ASCII OPERANDS AND INSTRUCTIONS 107‘Notice in the code section above that (1) no H (hex) indicator is needed for BCD numbers when using the DT directive, and (2) the use of the based relative addressing mode (BX + displacement) allows access to all three arrays with a single register BX In Program 3-7 the DB ditective is used to define ASCII values. This makes the LSD (least significant digit) be located at the highest memory location of the array. In VALUE], 37, the ASCII for 7 is in memory location 0009; therefore, BX ‘must be pointed to that and then decremented. Program 3-7 is repeated, rewritten with the full segment definition TITLE — PROG3-7 (EXE) ADDING ASCII NUMBERS PAGE — 60,132 MODEL SMALL [STACK 64 “DATA VALUET DB ‘06s9478127" ORG OTOH VALUE2 08 0779563678" ‘ORG —0020H. RESULT! DB 10 DUP (7) ORG —G030H. RESULT2 D8 10 DUP(?) CODE MAIN: — MOV” AX,@DATA MOV DS,AK CALL ASC_ADD ‘call ASCII addtion subroutine CALL CONVERT ‘call convert fo ASCII subroutine MOV AH.ACH INT 21H 190 back to DOS {THIS SUBROUTINE ADDS THE ASCII NUMBERS AND MAKES THE RESULT UNPACKED. ‘ASC_ADD PROC cic jelear the carry Mov cx,10 }Set up loop counter MOV BxX9 ‘point to LSD BACK: = MOV AL-VALUE1[8X) ‘move next byte of operand 1 ADC ALVALUEZ[BX) ‘add next byte of operand 2 AAA ‘adjust fo make it ASCII MOV — RESULTI[BX)AL ‘store ASCIi sum DEC Bx ‘point to next byte LOOP BACK RET ‘ASC_ADD ENDP STHIS SUBROUTINE CONVERTS UNPACKED BCD TO ASCII CONVERT PROC MOV’ BX.OFFSETRESULT1 BX points to BCD data MOV SLOFFSETRESULT2 ‘SI points to ASCII data © MOV CX05 ICXis toop counter BACK2 MOV AXWORDPTRIBX] —_“get next 2 ASCII bytes OR AX3030H ‘insert ASCII 3s, Mov WORD PTRISIJAX store ASCIl ADD BX2 Jinerement BCD pointer ADD S12 Jincrement ASC pointer oor BACK2 RET CONVERT ENOP END MAIN Program 3-7 108 CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONSTe PAGE STSEG STSEG bTSEG VALUE1 VALUE RESULT! RESULT2 OTSEG coses MAIN MAIN BACK: STHIS SUBROUTINE ADDS THE ASCII NUMBERS AND MAKES THE RESULT UNPACKED. |ASC_ADD PROC ‘ASC_ADD ENDP. STHIS SUBROUTINE CONVERTS UNPACKED BCD TO ASCII ‘CONVERT PROC MOV X05 {CXis loop counter BACK2: = MOV Ax WoRD PTRIBX] ‘get next 2 ASCII bytes OR ‘insert ASCII 3s Mov WORDPTRISIAX ‘Sere ASC ADD 8X2 increment BCD pointer ADD, Siz “increment ASCII pointer LOOP BACK? RET CONVERT ENDP CDSEG ENDS END MAIN PROGS 7 (EXE) REWRITTEN WITH FULL SEGMENT DEFINITION 60,132 SEGMENT DB 64DUP (7) ENDS ‘SEGMENT. Da ‘oeso47e127° ORG 00104 DB 0779569678" ORG 00208 0B 10 DUP (7) ORG 00304 DB 10 DUP (7) ‘SEGMENT PROC FAR ASSUME CS:COSEG,0S:DTSEG.SS.STSEG MOV AXOTSEG Mov DS,AX’ CALL ASC_ADD ‘xall ASCII addition subroutine CALL CONVERT convert to ASCII subroutine MOV AH.ACH INT 21H go back to DOS. ENOP cic selear the carry MOV CX.10 {sel up loop counter Mov BX9 {pont to LSD MOV AL|VALUE1[BX) [move next byte of operand 1 ADC —AL,VALUEZ{6X} add next byte of operand 2 AAA adjust to make it unpacked BCD NOV RESULTIIBXIAL store BCD sum DEC point to next byte Coop BACK RET MOV’ BX.OFFSET RESULT! 8X points to unpacked BCD data MOV SLOFFSETRESULT2 ‘Si points to ASCII data Program 3-7, rew fen with full segment definition ASCII addition and subtraction ASCII numbers can be used as operands in add and subtract instructions the way they are, without masking the tagged 011, using instructions AAA and AAS, MoV AL," VAL=35 0011 0101 ADD Al add to AL 32 the ASCII for 2 0011 0010 AAA changes 67H to 07H O10 0111 OR AL,30 JOR AL with 30H to get ASCII SECTION 3.4: BCD AND ASCII OPERANDS AND INSTRUCTIONS 109If the addition results in a value of more than 9, AAA will correct it and pass the extra bit to carry and add I to AH. SUB AH.AH mov AL?’ Mov BLS" ADD ALBL (CH therefore AL=6C. AAA jchanges 6CH to 02 in AL and AH: OR AX,3030H —;AX=3132 which is the ASCII for 12H. ‘Two facts must be noted. First, AAA and AAS work only on the AL register, and second, the data added can be unpacked BCD rather than ASCII, and AAA and AAS will work fine. The following shows how AAS works on subtraction of unpacked BCD to correct the result into unpacked BCD: Mov AX,105H :AX=0105H unpacked BCD for 15 Mov CL,06 sCL=06H SUB ALCL 1-6 =-1 (FFH) AAS. FFH in AL is adjusted to 09, and ‘AH is decremented, leaving AX = 0009 Unpacked BCD multiplication and division There are two instructions designed specifically for multiplication and division of unpacked BCD operands. They convert the result of the multiplication and division to unpacked BCD. AAM The Intel manual says that this mnemonic stands for "ASCII adjust multi- plication,” butit really is unpacked multiplication correction. If two unpacked BCD ‘numbers are multiplied, the result can be converted back to BCD by AM. Mov AL,7" H AND ALOFH unpacked BCD Mov DL’6" 0L=36H AND DL.OFH unpacked BCD MUL OL !AX=ALxDL. =07x06=002AH=42 AAM 102 (7x6=42 unpacked BCD) OR ‘AX,3030H 132 result in ASCII The multiplication above is byte by byte and the result is HEX. Using AAM converts it to unpacked BCD to prepare it for tagging with 30H to make it ASCII AAD Again, the Intel manual says that AAD represents "ASCII adjust for division," but that can be misleading since the data must be unpacked BCD for this, instruction to work. Before dividing the unpacked BCD by another unpacked BCD, AAD is used to convert it to HEX. By doing that the quotient and remainder are both in unpacked BCD. MOV AX,3539H ——_—|AX=3539. ASCII for $9 AND AX,OFOFH .AL=09 unpacked BCD data AAD !AX=003BH hex equivalent of 59 MOV BH,O8H ‘divide by 08 ow BH ‘3B / 08 gives AL=07 AH=03 OR AX,3030H —_|AL=37H (quotient) AH=33H (rem) 110 CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONSAs can be seen in the example above, dividing 59 by 8 gives a quotient of 7 and a remainder of 3. With the help of AAD, the result is converted to unpacked BCD, so it can be tagged with 30H to get the ASCII result. It must be noted that both AAM and AAD work only on AX. Review Questions 1, For the following decimal numbers, give the packed BCD and unpacked BCD rep- resentations, (a) 15 (b) 99 2. Match the following instruction mnemonic with its function, ___DAA DAS. as AAA (a) ASCII addition (b) ASCII subtraction {c) BCD subtraction (4) BCD addition SECTION 3.5: ROTATE INSTRUCTIONS. In many applications there is a need to perform a bitwise rotation of an operand. The rotation instructions ROR, ROL and RCR, RCL are designed specifi- cally for that purpose. They allow a program to rotate an operand right or left. In this section we explore the rotate instructions, which frequently have highly spe- cialized applications. In rotate instructions, the operand can be in a register or memory. If the number of times an operand is to be rotated is more than 1, this is indicated by CL. This is similar to the shift instructions. There arc two type of rotations. One is a simple rotation of the bits of the operand, and the other is a rotation through the carry. Each is explained below. Rotating the bits of an operand right and left ROR rotate right In rotate right, msB LsB as bits are shifted from left to right they exit CF from the right end (LSB) and enter the left end (MSB). In addition, as each bit exits the LSB, a copy of itis given to the carry flag. In other words, in ROR the LSB is moved to the MSB and is also copied to CF, as shown in the diagram. If the operand is to be rotated once, the 1 is coded, but if itis to be rotated more than once, register CLis used to hold the number of times it is to be rotated. MOV AL36H ROR ALA ROR AL1 ROR ALA or: MOV AL,36H. Mov CL3 ROR ALCL :the operand can be a word: MOV 8X,0C7ESH MOV CL ROR BX,CL number of times to rotate 100 0110 CF=1 sBX=1100 0111 1110 0101 :CL=6 number of times to rotate =1001 0111 0001 1111 CF=1 SECTION 3.5: ROTATE INSTRUCTIONS iiROL rotate left In rotate left, as cr MsB LSB bits are shifted from right to left they exit the left end (MSB) and enter the right end (LSB). In addition, every bit that leaves the MSB is copied to the carry flag. In other words, in ROL the MSB is moved to the LSB and is also copied to CF, as shown in the diagram. Ifthe operand is to be rotated once, the I is coded. Otherwise, the number of times itis to be rotated is in CL. MOV BH,72H :BH=0111 0010 ROL BH,1 ;BH=1110 0100 CI ROL BH.t :BH=1100 1001 CF=1 ROL BH,t 4 ROL BH,t q or: MOV BH,72H ;BH=0111 0010 Mov CL4 :CL=4 number of times to rotate ROL BH.CL :BH=0010 0111 CF=1 ‘The operand can be a word: MOV) DX,672AH —:DX=0110 0111 0010 1010 MOV CL3 :CL=3 number of times to rotate ROL _DX.CL {0X=0011 1001 0101 0011 CF=1 Write a program that finds the number of Is in a byte From the data segment: DATAL. DB O7H COUNT DB? From the code sogment: ‘SUB BL.BL :clear BL to keep the number of 1s, MOV OL8 ‘rotate total of 8 times MOV ALDATAT AGAIN: ROL ALA srotate it once NC NEXT icheck for 4 INC BL ECF=1 then add one to count NEXT. DEC DL {go through this 8 times. NZ AGAIN Ht not finished go back Mov __COUNTBL__‘save he number of 1s Program 3-8 Program 3-8 shows an application of the rotation instruction. The maxi- ‘mum count in Program 3-8 will be 8 since the program is counting the number of 1s ina byte of data. If the operand is a 16-bit word, the number of Is can gos high as 16. Program 3-9 is Program 3-f, rewritten for a word-sized operand, It also provides the count in BCD format instead of hex. Reminder: AL is used to make a BCD counter because the DAA instruction works only on AL. Wile a program lo count the number of 1s in a word. Provide the count in BCD. DATAW! DW O7F4H COUNT2 DB? SUB ALAL clear AL to keep the numberof 1s in BCD Mov L1G yrolate total of 16 times MOV BX,DATAW1 move the operand to BX AGAIN, ROL BX4 ‘rolate it once SNC NEXT Ioheck for 1. IfCF=0 then jump ADD ALA SCF=1 then add one to count DAA ‘adjust the count for BCD NEXT, DEC DL {0 through this 16 times JNZ AGAIN if not finished go back MoV COUNT2AL ‘save the number of 15 in COUNT2 Program 3-9 2 CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONSRCR rotate right through carry In RCR, as bits are shifted from left to right, they exit the right end (LSB) to the carry MSB LsB CF flag, and the carry flag enters the left end (MSB). In other words, in RCR the LSB is moved to CF and CF is moved to the MSB, In reality, CF acts as if it is part of the operand. This is shown in the diagram Ifthe operand isto be rotated once, the 1 is coded, but if itis to be rotated more than once, the register CL holds the number of times. Le smake CF=0 MOV AL,26H 10 0110, RCR ALA ;AL=0001 0011 CF=0 RCR ALA ;AL=0000 1001 Cf RCR ALA ;AL=1000 0100 CF=1 or: cic make CF=0 MOV AL,26H 10 0110 MOV CL3 number of times to rotate RCR ALCL ‘AL=1000 0100 CF=1 ithe operand can be a word STC smake CF=1 MOV BX37FIH 3B MOV CLS :CL=5 number of times to rotate RCR BX,CL }BX=0001 1001 1011 1111 CF=0 RCL rotate left through carry In RCL, as bits are shifted from right o left they exit the left end (MSB) and CF enter the carry flag, and the carry flag enters the right end (LSB). In other words, in RCL the MSB is moved to CF and CF is moved to the LSB. Inreality, CF acts as i itis part ofthe operand. This is shown in the diagram. Ifthe operand is to be rotated once, the | is coded, but if it isto be rotated more than once, register CL holds the number of times. MsB. SB sTc MOV BL,15H RCL BLt RCL BLA or: sTc smake CF=1 MOV BL,15H ;BL=0001 0101 Mov CL2 :CL=2 number of times for rotation RCL BL,CL ;BL=0101 0110 CF=0 sthe operand can be a word: cic smake CF=0 MOV AX,191CH —:AX=0001 1001 0001 1100 MOV CLS :CL=5 number of times to rotate RCL AX,CL :AX=0010 0011 1000 0001 CF=1 SECTION 3.5: ROTATE INSTRUCTIONS 13SECTION 3.6: Review Questions What is the value of BL after the following? MOV BL25H MOV CL4 ROR BLCL ‘What ate the values of DX and CF after the following? MOV DX,3FA2H MOV CL7 ROL DX,CL ‘What is the value of BH after the following? SUB BH,BH STC RCR BHA sTC RCR BH,1 What is the value of BX after the following? MOV BX,FFFFH MoV L's cic RCL BX,cL Why does "ROR BX,4" give an error in the 8086? How would you change the code to make it work? BITWISE OPERATION IN THE C LANGUAGE One ofthe most importantand pow- ‘Table 3-4: Bitwise AND, OR, erful features of the C language iss ability and EX-OR in to perform bit manipulation, Duc to the fact that many books on C do not cover this x important topic, itis appropriate todiseussit_ |-A-B_ A&B’ ALBLA*B in this section. This section describes the | 0 | 0| 0 | o | 0 actin of operaiors and provideseamptes. |~y fy | [a4 Bitwise operators in C stololalo Whileevery Cprogrammeristami- [1 [1 [1 | 4 | o iar with the logical operators AND (8.8), ‘OR (\), and NOT (1), many C programmers are less familiar with the bitwise operators AND (&), OR (\), Table 3-5: Bitwise EX-OR(*),inverter(-),Shift Right(>>),andShiftLett ‘Inverter in C (<6), These bitwise operators are widely used in soft- ware engineering and control; consequently, their un- A derstanding and mastery are critical in system design and interfacing. See Tables 3-4 and 3-5. The following 0 1 code shows Examples 3-5 through 3-7 using the C 1 0 logical operators. Recall that "Ox" in the C language indicates that the data is in hex format. 0x35 & OxOF = 0x05. /* ANDing; see Example 3-5 */ (0x0504 | OxDAGE = OxDFEC —_/* ORing: see Example 3-6 */ 0x54 * 0x78 = 0x20 /* XORing: see Example 3-7 */ ~0x37 = OxCB ?* inverting 37H *) ‘The last one is like the NOT instruction in x86 microprocessors: MOV AL,37H_— jAL=37H NOTAL :AFTER INVERTING 37, AL=C8H 114 CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONSBitwise shift operators in C ‘There are two bitwise shift operators in C: Shift Right (> >) and Shift Left (<<). They perform exactly the same operation as SHR and SHL in Assembly language, as discussed in Section 3.3. Their format in C is as follows: data >> number of bits to be shifted _/* shifting right */ data << number of bits to be shifted —_/* shifting left */ ‘The following shows Examples 3-9 through 3-11 using shift operators in C. Program 3-10 shows all of these examples with C syntax. OK9A >> 3 = 0x13 P* shifting right 3 times: see Example 3-9 */ 0x7777 >>4 = 0x0777—_* shifting right 4 times: see Example 3-10 */ 0x6 << 4 0x60 /* shifting left 4 times: see Example 3-11 */ 7 Program 3-10 Repeats Examples 5-5 through 3-11 in © *7 include
main() { I) Notice the way data is defined in C for Hex format using Ox unsigned char data_1 = Ox35; unsigned int data_2"= 0x504 unsigned int data_3 = OxDa‘ unsigned char data_4= 0x54; unsigned char data 50x78; unsigned char data_6=0x37; unsigned char data~7=0x09A; unsigned char temp; unsigned int temp_2; temp=data_1&0x0F; JIANDing printf("\nMasking the upper four bits of 96X (hex) we get %X (hex)\n’.data_1,temp); temp 2edata 2ldata 3: //ORing printf("The result of 96X hex ORed with %X hex is %X hexin*,data_2,data_3,temp_2); temp=data_4*data 5; /EX-ORing printiThe results oT 6X hex EX-ORed with 96x hex is %X hextn".data_4.data_6,temp); temp=-data INVERTING print{("The result of 9X hex inverted is %X hex\n",data_6 temp); temp=data_7>>3; JISHIFTING Right printi("When %X hex is shifted right three times we get %X hexin"data_7,temp); print{("When %X hex is shifted right four times we get %X hex\n",0X7777,0x7777>>4); temp=(0x6<<4); JISHIFTING Lett printf("When %X hex is shifted left %d times we get 9X hexin',0x6,4,temp); + Program 3-10 Program 3-10 demonstrates the syntax of bitwise operators in C. Next we show some real-world examples of their usage. SECTION 3.6: BITWISE OPERATION IN THE C LANGUAGE usPacked BCD to ASCII conversion in C Scction 3.4 showed one way {0 convert a BCD number to ASCII. This conversion is widely used when dealing with a real-time clock chip. Many of the real-tim chips provide very accurate time and date for up to ten years without the need for external power. There is a real-time clock in every x86 IBM PC or compatible computer. However, these chips provide the time and date in packed BCD. In order to display the data, it needs to be converted to ASCI. Program 3-11 isa Cversion of the packed BCD-1o-ASCII conversion example discussed in Section 3.4. Program 3-11 converts a byte of packed BCD data into two ASCII characters and displays them using the C bitwise operators. ) Program 3-11 printf(*My BCD data is %c if not converted to ASCII F Program 3-11 shows packed BCD -to-ASCII conversion using logical bitwise operators in © *7 Winclude
main) { unsigned char mybed=0x29; /* declare a BCD number in hex */ unsigned char asci_ unsigned char asci_2; asci_1=mybed&0xOt, /* mask the upper four bits */ asci_1=asci_1]0x30; /# make it an ASCII character */ asci_2=mybed&Oxt0; /* mask the lower four bits */ asci_2qasci_2>>4: /* shift it right 4 times */ asci_2=asci_2[0x30; /* make it an ASCII character */ printi(“BCD data %X is 9c . %c in ASCil\n*,mybed.asci_1,asci_2); bed); Notice in Program 3-11 that if the packed BCD data is displayed without conversion to ASCIL, we get the parenthesis ")". See Appendix F. Testing bits in C In many cases of system programming and hardware interfacing, it is necessary 10 testa given bit to sec if it is high. For example, many devices send a high signal to state that they are ready for an action or to indicate that they have data. How can the bit (or bits) be tested? In such cases, the unused bits are masked and then the remaining data is tested. Program 3-12 asks the user for a byte and tests to see whether or not DO of that byte is high 7 Program 3-12 ‘maing printi(\nType in jatus&0x01; ‘shows how to test bit DO to see ifitis high *7 Hinclude
{ unsigned char status; unsigned char temp; ‘a Hex value\n’); scan{("%6X",&sialus); Jiget the data i}mask all bits except D0 ifs it high? ifityes, say so else printf("DO is low"); Ift ne, say no } Program 3-12 116 CHAPTER3: ARITHMETIC AND LOGIC INSTRUCTIONS.SUMMARY PROBLEMS L BY Srawsene The assembly language version of Program 3-12 is as follows: :MASK ALL BITS EXCEPT DO 31S DO HIGH JNE BELOW IMAKE A DECISION . :YES DOIS HIGH BELOW: :D0 IS LOW Review Questions What is the result of 0x2F&0x27 ? What is the result of 0x2F|0x27 ? ‘What is the result of 0x2F*0x27 ? ‘What is the result of ~0x2F ? What is the result of 0x2F >> 3 ? ‘What is the result of 0x27 << 4? In Program 3-11 if mybed=0x32, what is displayed if it Modify Program 3-12 to test D3. not converted to BCD? ‘The 8- or 16-bit data items in 80x86 computers can be treated as either signed or unsigned data. Unsigned data uses the emtire 8 or 16 bits for data representation. Signed data uses the MSB as a sign bit and the remaining bits for data representation. This chapter covered the arithmetic and logic instructions that ‘are used for unsigned data. The instructions ADD and SUB perform addition and subtraction on unsigned data. Instructions ADCand SBB do the same, butalso take the carry flag into considcration. Instructions MUL and DIV perform multiplication and division on unsigned data. Logic instructions AND, OR, XOR, and CMP perform logic operations on all the bits of their operands and were therefore included in this chapter. ‘Shift and rotate instructions for unsigned data include SHR, SHL, ROR, ROL, RCL, and RCR. ASCII and BCD data operations for addition and subtraction were also covered. Finally, bitwise logic instructions were demonstrated using the Clanguage. Find CF, ZF, and AF for cach of the following. Also indicate the result of the addi- tion and where the result is saved. (a) MOV BH,3FH (b) MOV DX,4599H (MOV AX,255 ‘ADD BHASH MOV CX)3458H sTC ADD CX,DX ADC AX,00 (d) MOV BX,OFFOIH (©) MOV CX\OFFFFH (Q) MOV AHOFEH ‘ADD BL,BH sTC sTC ADC CX,00 ADC AH,00 Write, run, and analyze a program that calculates the tal sum_paid to a salesper- son for eight months. The following are the monthly paychecks for those months: $2300, $4300, $1200, $3700, $1298, $4323, $5673, $986, Rewrite Program 3-2 (in Section 3.1) using byte addition. Write a program that subtracts two multibytes and saves the result. Subtraction should be done a byte at a time. Use the data in Program 3-2. ‘State the three steps involved in a SUB and show the steps for the following data (a) 23H-12H (b) 43H-51H (©) 99.99, Write, run, and analyze the result of a program that performs the foliowing: (1)(a) bytet x byte2 (b) bytel x wordt (©) word! x word2 (2) (a) bytet /byte2 (b) word / word2 (¢) doubleword/bytet Assume byte1=230, byte2=100, word1=9998, word2=300 and doubleword =100000. SUMMARY 1177 Assume that the following registers contain these HEX contents: AX = F000, BX ~ 3456, and DX = £390. Perform the following operations. Indicate the result and the register where it is stored. Give also ZF and CF in each case, ‘Note: the operations are independent of each other, (a) AND DX,AX (b) OR DH.BL (c) XOR AL, 76H (d) AND DX,DX (e) XOR AX,AX. (f) OR BX,DX (g) AND AH,OFF (h) OR AX,9999H_ (i) XOR DX,OEEEEH () XOR BX,BX (k) MOV CL,04 (I) SHR DX,! SHL ALCL (m) MOV CL3 (1) MOV CLS SHR DLCL SHL BX,CL (0) MOV CL,6 SHL DX,CL_ 8. Indicate the status of ZF and CF after CMP is executed in each of the following, cases. (a) MOV BX,2500 (b) MOV AL,OFFH (c) MOV DL,34 CMP BX,1400 (CMP AL,6FH CMP DL,88 (d) SUB AX,AX (e) XOR DX,DX (f) SUB CX,CX CMP AX,0000 CMP DX,0FFFFH DEC CX CMP CX,0FFFFH (g) MOV BX,2378H (h) MOV AL,OAAH MOV DX,4000H AND AL,SSH_ (CMP DX,BX CMP AL,00 9, Indicate whether or not the jump happens in each case. (a) MOV CL,5 (b) MOV BH,65H (c) MOV AH, SSH. SUB AL,AL_ MOV AL,48H. SUB DL,DL SHL ALCL OR AL,BH OR DL,AH JNC TARGET SHLAL,1 MOV CL,AH JC TARGET AND CL,OFH SHR DL,CL INC TARGET 10. Rewrite Program 3-3 to find the lowest grade in that class IL. Rewrite Program 3-4 to convert all uppercase letters to lowercase. 12. Inthe IBM BIOS program for testing flags and registers, verify every jump (con- ditional and unconditional) address calculation. Reminder: As mentioned in Chapter 2, in forward jumps the target address is calculated by adding the dis- placement value to IP of the instruction after the jump and by subtracting in back- ‘ward jumps. 13. In Program 3-6 rewrite BCD_ADD to do subtraction of the multibyte BCD. 14. Rewrite Program 3-7 to subtract DATA2 from DATAI. Use the following data. DATAI DB "0999999999" DATA2 DB 0077777775" 15. Using the DT directive, write a program to add two 10-byte BCD numbers. 16. We would like to make a counter that counts up from 0 to 99 in BCD. What in- struction would you place in the dotted area? SUB AL,AL ADD AL,] 17. Write Problem 16 to count down (from 99 to 0), 18. An instructor named Mr. Mo Allem has the following grading policy: "Curving of ‘grades is achieved by adding to every grade the difference between 99 and the highest grade in the class." If the following are the grades of the class, write a program to calculate the grades after they have been curved: 81, 65, 77, 82, 73, 55, 8, 78, 51, 91, 86, 76. Your program should work for any set of grades. 19. If we try to divide 1,000,000 by 2: (a) What kind of problem is associated with this operation in 8086/286 CPUs? (b) How does the CPU let us know that there is a problem? 118 (CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONS20. Which of the following groups of code perform the same operation as LOOP. XXX? (a)DECCL (b)DECCH (¢)DECBX — (d) DECCX JNZXXX ——INZXXX NZ INZ XXX 21. Write a program that finds the number of zeros in a 16-bit word. 22. In Program 3-2, which demonstrated multiword addition, pointers were updated by two INC instructions instead of "ADD SI,2". Why? 23. Write a C program with the following component: (a) have two hex values: datal=5SH and data2=AAH; both defined as unsigned char, (b) mask the upper 4 bits of datal and display it in hex, (©) perform AND, OR, and EX-OR operations between the two data items and then display each result, (d) invert one and display it, (e) shift left datal four times and shift right data? two times, then display each result. 24, Repeat the above problem with two values input from the user. Use the scanf("%X") function to get the hex data. 25, In the same way that the real-time clock chip provides data in BCD, it also ex- pects data in BCD when itis being initialized, However, data coming from the keyboard is in ASCII, Write a C program to convert two ASCII bytes of data to packed BCD. 26. Write aC program in which the user is prompted for a hex value. Then the data is, tested to see if the two least significant bits are high. If'so, a message states "DO and D1 are both high"; otherwise, it states which bit is not high. 27. Repeat the above problem for bits DO and D7. ANSWERS TO REVIEW QUESTIONS SECTION 3.1 UNSIGNED ADDITION AND SUBTRACTION destination 2. Fremnae Aasertty inguage, thee ae no memory to memory operons 3. MOV AX.DATA 2 ADD DATA_1,AX 4. destination, Source + destination + CF 3 in(a. the byte addon resus na cary to CF in (0), the word aon resutin a cary to the high byte BH NZ. ADD_LOOP 7. “43H 07000011 100 0011 =05H 00000101 2's complement=+1111 1011 3EH oor TT0 CF=0; therefore, the result Is positive 8. AL=95-4F-1= 45 SECTION 3.2: UNSIGNED MULTIRLICATION AND DIVISION X and AX 3. AX 4. AL,AH 5. AX,DX 5 can TAX, OX SECTION 33: LOGIC INSTRUCTIONS AND SAMPLE PROGRAMS (a) 4202 (b) CREF (c) BDFD 2 Re operand wil remain unchanged: Si Zeros 3. all ones 4. all zer0s 5. AOF2= 1010 0000 1111 0010 shiftlet: 0100 0001 1110 0100 CF = shift again: 1000 0011 1100 1000 CF =0 shift again: 0000 0111 1001 0000 CF =t ‘AOE2 shifted left three times = 0790. AOF2= 1010 0000 1111 0010 shiftright: 0101 0000 0111 1001 CF =0 shift again: 0010 1000 0011 1100 CF=1 shift again: 0001 0100 0001 1110 GF =0 ‘AOF2 shifted right three times = 141 6. SUB 7.talse ANSWERS TO REVIEW QUESTIONS 119SECTION 3.4: BCD AND ASCII OPERANDS AND INSTRUCTIONS + (a) 15 = 0007 0101 packed BCD = 0000 0004 0000 0101 unpacked BCD (b) 99 = 1001 1001 packed BCD = 0000 1001 0000 1001 unpacked BCD 2. DAA~ BCD aasition; DAS ~ BCD subtraction; AAS -- ASCII subtraction; AAA-- ASC adcition SECTION 3.5: ROTATE INSTRUCTIONS 1. BL=§2H, CF =0 2. DX = DIIFH. CF 3. BH=COH 4, BX = FFEFH '5. the source operand cannot be immediate; to fx MOV CL, ROR BX.CL SECTION 3.6: BITWISE OPERATION IN THE C LANGUAGE 1. oa? 2 ox2F 3. 0x08 4) O00 5. 0x05, 6 0x70 72 8 This program shows how to test Bit D3 to see ifitis high include
rain) Unsigned char status; Unsigned char temp, printf'\wnType in a Hex value’ Sscan{("%X" Status) temp=statusé0x04: if (temp==x04) printf("D3 is high’); pie prise ow 120 CHAPTER 3: ARITHMETIC AND LOGIC INSTRUCTIONS
You might also like
8051-CH6-ArithLigic Instructns
PDF
100% (1)
8051-CH6-ArithLigic Instructns
114 pages
2 - Data Transfer
PDF
No ratings yet
2 - Data Transfer
22 pages
Chapter 4
PDF
No ratings yet
Chapter 4
92 pages
Computer & Interfacing Chapter FOUR NEW UPDATED
PDF
No ratings yet
Computer & Interfacing Chapter FOUR NEW UPDATED
93 pages
Microproccessor NOTES
PDF
No ratings yet
Microproccessor NOTES
55 pages
3-Arithmetic and Logic Instructions
PDF
No ratings yet
3-Arithmetic and Logic Instructions
83 pages
MM 2
PDF
No ratings yet
MM 2
266 pages
MPMC Lab
PDF
No ratings yet
MPMC Lab
62 pages
Micro - Lecture (CH 3)
PDF
No ratings yet
Micro - Lecture (CH 3)
30 pages
MM Module2 Cse Notes PDF
PDF
No ratings yet
MM Module2 Cse Notes PDF
54 pages
Arithmetic & Logic Instructions and Programs: The 8051 Microcontroller and Embedded Systems: Using Assembly and C
PDF
No ratings yet
Arithmetic & Logic Instructions and Programs: The 8051 Microcontroller and Embedded Systems: Using Assembly and C
44 pages
Chapter 4 - Arithmetic and Logic Instructions
PDF
No ratings yet
Chapter 4 - Arithmetic and Logic Instructions
47 pages
micro - lecture-ch-3اءع ؤ
PDF
No ratings yet
micro - lecture-ch-3اءع ؤ
30 pages
88 86 I Programming
PDF
No ratings yet
88 86 I Programming
46 pages
8051 Isa
PDF
No ratings yet
8051 Isa
27 pages
4-Arithmetic Instruction
PDF
No ratings yet
4-Arithmetic Instruction
17 pages
Chapter3 - Arithmetic and Logic Instructions
PDF
No ratings yet
Chapter3 - Arithmetic and Logic Instructions
54 pages
Part 2
PDF
No ratings yet
Part 2
125 pages
Name: Haris Shabbir Section:3B SAP ID: 70077931
PDF
No ratings yet
Name: Haris Shabbir Section:3B SAP ID: 70077931
13 pages
L5 Arithmetic Logic and Shift Instr
PDF
No ratings yet
L5 Arithmetic Logic and Shift Instr
13 pages
Chandigarh University: University Institute of Engineering
PDF
No ratings yet
Chandigarh University: University Institute of Engineering
50 pages
Fall 2018/19 - Lecture Notes # 8: - Unsigned Addition and Subtraction - Addition of Multiword Numbers
PDF
100% (1)
Fall 2018/19 - Lecture Notes # 8: - Unsigned Addition and Subtraction - Addition of Multiword Numbers
7 pages
8086 - Arithmetic Logic Unit
PDF
No ratings yet
8086 - Arithmetic Logic Unit
11 pages
CH 6 - Arithmetic, Logic Instructions and Programs
PDF
No ratings yet
CH 6 - Arithmetic, Logic Instructions and Programs
35 pages
Chapter 5
PDF
No ratings yet
Chapter 5
74 pages
MPECC08 Practical File
PDF
No ratings yet
MPECC08 Practical File
13 pages
Microcomputer & Interfacing - Teaching
PDF
No ratings yet
Microcomputer & Interfacing - Teaching
30 pages
A2 - 271046 - Pratham Raka - MP - Assingment - 4
PDF
No ratings yet
A2 - 271046 - Pratham Raka - MP - Assingment - 4
8 pages
The Women University, Multan
PDF
No ratings yet
The Women University, Multan
13 pages
8086 Instructions
PDF
No ratings yet
8086 Instructions
27 pages
Arithmetic Instructions
PDF
No ratings yet
Arithmetic Instructions
30 pages
09 P3, P4 Cumulative Sum
PDF
No ratings yet
09 P3, P4 Cumulative Sum
6 pages
Microprocessor Programming I
PDF
No ratings yet
Microprocessor Programming I
46 pages
Unit II: Instruction Set and Addressing Modes
PDF
No ratings yet
Unit II: Instruction Set and Addressing Modes
53 pages
Arithmetic & Logic Instructions and Programs: The 8051 Microcontroller and Embedded Systems: Using Assembly and C
PDF
No ratings yet
Arithmetic & Logic Instructions and Programs: The 8051 Microcontroller and Embedded Systems: Using Assembly and C
50 pages
Lecture 3
PDF
No ratings yet
Lecture 3
52 pages
Arithmetic and Logic Instructions
PDF
No ratings yet
Arithmetic and Logic Instructions
83 pages
Arithmentic 24
PDF
No ratings yet
Arithmentic 24
23 pages
PS1
PDF
No ratings yet
PS1
20 pages
ECE 426 Exam 1 Solved
PDF
No ratings yet
ECE 426 Exam 1 Solved
5 pages
CE 302 Microprocessors Week 7
PDF
No ratings yet
CE 302 Microprocessors Week 7
79 pages
Exp-No4 Add 8 Bit and 16-Bit Numbers
PDF
No ratings yet
Exp-No4 Add 8 Bit and 16-Bit Numbers
3 pages
Micro Imp Da
PDF
No ratings yet
Micro Imp Da
30 pages
EEE-363 L3T2 20eee Class-8
PDF
No ratings yet
EEE-363 L3T2 20eee Class-8
12 pages
Instruction Set
PDF
No ratings yet
Instruction Set
161 pages
LAB 5 Arithmetic Instructions - (Updated)
PDF
No ratings yet
LAB 5 Arithmetic Instructions - (Updated)
25 pages
MP Lect 4
PDF
No ratings yet
MP Lect 4
37 pages
EE234 - Lec - 03
PDF
No ratings yet
EE234 - Lec - 03
45 pages
Mic Unit III
PDF
No ratings yet
Mic Unit III
70 pages
Ders 7
PDF
No ratings yet
Ders 7
91 pages
Sunu4 Arithmetic, Logic and Control Instructions2012
PDF
No ratings yet
Sunu4 Arithmetic, Logic and Control Instructions2012
45 pages
CSC 202 Low Level Language Manual
PDF
No ratings yet
CSC 202 Low Level Language Manual
51 pages
Lec7 Arithmetic
PDF
No ratings yet
Lec7 Arithmetic
36 pages
6-Arithmetic and Logic Instructions
PDF
No ratings yet
6-Arithmetic and Logic Instructions
13 pages
Instruction Set 8086
PDF
No ratings yet
Instruction Set 8086
16 pages