0% found this document useful (0 votes)
18 views54 pages

7 Branching 6 Exercises To Solve Conditional Jumps and High Level To Assembly Conversion

The document discusses conditional processing in assembly language, focusing on unconditional and conditional jumps, including their syntax and applications. It explains how to implement various control structures like IF statements, WHILE loops, and CASE statements using assembly code, along with examples. Additionally, it covers the use of flags for decision-making and the implementation of compound conditions using AND and OR logic.

Uploaded by

Armish Aamir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views54 pages

7 Branching 6 Exercises To Solve Conditional Jumps and High Level To Assembly Conversion

The document discusses conditional processing in assembly language, focusing on unconditional and conditional jumps, including their syntax and applications. It explains how to implement various control structures like IF statements, WHILE loops, and CASE statements using assembly code, along with examples. Additionally, it covers the use of flags for decision-making and the implementation of compound conditions using AND and OR logic.

Uploaded by

Armish Aamir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Conditional Processing

Assembly Language Programming


Unconditional Jump
• JMP [operator] destination
Instruction Label
A symbolic name defined to be an address in the
code segment of a program
A label may be attached to any point in the code
of a program
a_Label: jmp a_Label
Labels definitions usually have a colon at the end
Conditional Jumps
A conditional jump instruction branches to a label when
specific register or flag conditions are met

• Jxxx destination
› There are 30 some variations that interrupt
sequential flow based on various flag settings
• JNZ - Jump if zero flag is clear (0) meaning
the result of a previous operation was non-
zero
• JC - Jump if a previous operation caused
the carry flag to be set (1)
Range of Conditional Jumps
• All conditional jumps are SHORT
› range is -128 to +127 bytes
› 80386+ allow larger distances
• Combine a conditional and unconditional jump
to overcome this range limitation
Unconditional Jump Instruction JMP:
Syntax: JMP destination_label
Cause Unconditional transfer of control to destination
label , usually a label in the same segment as the JMP itself.
Can be used to avoid Range restriction of conditional
Jumps (-128 and 127 byte) for example if the body contain
so many instructions that label TOP is out of range for JNZ ,
then JMP unconditional jump alternative is used thus:

TOP: TOP:
.; body of the loop ; body of the loop
DEC CX DEC CX
JNZ TOP JNZ BOTTOM
MOV AX,BX JMP EXIT
BOTTOM:
JMP TOP
EXIT:
MOV AX,BX
Using Conditional Jumps
• Conditional jumps typically follow an instruction
that alters the flag bits
› CMP destination, source
› Computes (destination-source) and sets flag bits
• result is not stored
• flags allow us to decide <, <=, >, >=, ==, <>, etc
• we can also interpret the results meaningfully for
signed or unsigned data
Like SUB inst. Except destination content will not changed
CMP AX,BX ; where AX= 7FFF and BX=0001 h, thus
JG BELOW ; result = 7FFF-0001h= 7FFEh
From table in the next slide it is clear that jump condition is
satisfied, since : flags Z=S=O=0 control is transferred to
Label BELLOW , if signed interpretation is used.
When two unsigned operands are compared , the Zero, and carry Flags indicate the
following relation between operands

CMP Results ZF CF
Destination <source 0 1
Destination > source 0 0
Destination =source 1 0

When two signed operands are compared , the sign , and overflow Flags indicate the
following relation between operands

CMP Results Flags


Destination <source SF OF
Destination > source SF=OF
Destination =source ZF=1
Conditional Jump

Signed Jumps:
Unsigned conditional Jumps :
Single–Flag Jumps
Applications
• Task: Jump to a label if unsigned AX is greater than BX
• Solution: Use CMP, followed by JA

cmp ax,bx
ja Larger

• Task: Jump to a label if signed AX is greater than BX


• Solution: Use CMP, followed by JG

cmp ax,bx
jg Greater
Applications

• Compare unsigned AX to BX, and copy the larger of the two


into a variable named Large
mov Large,bx
cmp ax,bx
jna Next
mov Large,ax
Next:

• Compare signed AX to BX, and copy the smaller of the two


into a variable named Small
mov Small,ax
cmp bx,ax
jnl Next
mov Small,bx
Next:
How The CPU Implement the Conditional Jump?
To implement a conditional jump, the CPU looks at the FLAGS register .
You already know it reflects the result of the last thing the processor did.
If the conditions for the Jump ( expressed as a combination of status flag
settings ) are true, the CPU adjust the IP to point to the destination label,
so that the instruction at this label will be done next. If the Jump
condition if false, then IP is not altered; this means that next instruction
in line be done.
Example: Program to display the IBM -256 ASCII code using :
Conditional Jump Inst. JNZ , Jump if not zero.
Counter Register –CX is the loop counter, its initialized by 256 and is
decremented after each character ,is displayed
JNZ inst. Is used to control the Print_Loop,
CPU execute it by testing ZF, if ZF=0, control transfer to Print_Loop
otherwise ,ZF=1 , the program execute the inst. : MOV Ah,4ch
TITTLE PGM6_1: IBM Character Display
. Model Small
.Stack 100h
.code
MAIN PROC
MOV Ah,2
MOV CX, 256d
MOV DL,0
Print_Loop:
INT 21h
INC DL
DEC CX
JNZ Print_Loop
MOV Ah,4ch
INT 21h
MAIN ENDP
END MAIN
Block-Structured IF Statements
Assembly language programmers can easily translate logical
statements written in C++/Java into assembly language. For example:
False True
IF condition is true Condition

THEN True-branch
execute true-branch statement Statement
END_IF

mov ax,op1
cmp ax,op2
if( op1 == op2 ) jne L1
X = 1; mov X,1
else jmp L2
X = 2; L1: mov X,2
L2:
Example; Implement the following pseudocode in assembly language. All
values are unsigned:

if( bx <= cx ) cmp bx,cx


ja next
{
mov ax,5
ax = 5; mov dx,6
dx = 6; next:
}
Implementing an IF-THEN
unsigned int n; ;if (n>7)
if (n>7) do_it(); mov ax,n
• If n is a signed int, use cmp ax,7
jna skip_it
jng (not greater)
;then-part
• unsigned:
call do_it
› above, below
;end if
• signed skip_it:
› less, greater
Implementing an IF-ELSE

char n; ;if (n=='7')


if (n=='7') cmp n,'7'
jne else_
do_it();
;then-part
else call do_it
do_that(); jmp short endif
• Document the control else_:
structures and keep the call do_that
parts in the usual order endif:
IF-THEN-ELSE
IF condition is True
THEN
Execute TRUE-BRANCH statement
ELSE
Execute TRUE-BRANCH statement

FALSE TRUE
Condition

False Branch True Branch


Statement Statement
• Example: Suppose AL and BL contain extended ASCII characters.
Display the one that comes first in the character sequence.
Solution:
If AL<= BL MOV AH,2 ; prepare for display
THEN CMP AL,BL ; AL<=BL ?
Display the char. In AL JNBE ELS_ ; No,display char in BL
ELSE MOV DL,AL
Display the Char. In BL JMP Display
End_IF ELS_: MOV DL,BL ; BL<AL
Display :
INT 21h ; Display it
End_IF:
The condition AL<=BL is expressed by (CMP AL,BL) , JNBE is used
because we are comparing extended characters. If AL<=BL is true ,the
true branch statements are done. Note that JMP Display is needed to
skip the false branch. This is different from that high-level language
IF_THEN_Statement in which false branch is automatically skipped if
the true branch statements are done.
Your turn . . .

Implement the following pseudocode in assembly


language. All values are 16-bit signed integers:

if( var1 <= var2 ) mov ax,var1


cmp ax,var2
var3 = 10;
jle L1
else mov var3,6
{ mov var4,7
var3 = 6; jmp L2
var4 = 7; L1: mov var3,10
} L2:
CASE:
Is a Multi-ways branch structure
that tests a register variable or Expression
Expression for certain value,
Syntax:
Value 1 Value 2 Value n
CASE expression
Value_1: Statement-1
Statement1 Statement2 Statement n
Value_2: Statement-2

Value_n: Statement-n
END-CASE
• Example : if A contain negative number put -1 in BX; AX contain
0, put 0 in BX, if AX contains a positive number , put in BX:
Pseudo Algorithm: ASSEMBL CODE
CASE AX ; case AX
< 0: put -1 in BX CMP AX,0
=0 : put 0 in BX JL NEGATIVE ; AX<0
>0 : put 1 in BX JE ZERO ; AX=0
END_CASE JG POSITIVE ; AX>0
NEGATIVE: MOV BX,-1
JMP END_CACE
ZERO: MOV BX,0
JMP END_CACE
POSITIVE: MOV BX, 1
END_CACE :
• Example: Assembly Code
If AL contains 1 or 3 , display “O” ;case AL=1,3
If AL contains 2 or 4, display “e” CMP AL,1 ; AL=1 ?
Pseudo Algorithm: JE ODD ; yes display “O”
CASE AL CMP AL,3 ; AL=3
1,3: display “O” JE ODD ; yes display “O’
2,4: display “e” ; case AL=2,4
END_CASE CMP AL,2
JE EVEN ; yes, display “e”
CMP AL,4
JE EVEN ; yes, display “e”
JMP END_CASE
ODD: MOV DL,”O”
JMP DISPLAY
EVEN: MOV DL,”e”
DISPLAY: MOV AH,2
INT 21H
END_CASE:
WHILE_LOOP:
Entry to this loop depends on a
condition , the loop pseudo
algorithm False True
WHILE condition DO Condition

Statements
END_WHILE
Statements

The condition is checked at the top , before entry of the loop. If


true , the statements are executed else the program bypass the
loop-body to following code. It is possible that condition is false
initially , in which case the loop –body is not executed at all
The loop executes as long as the condition is true.
WHILE Loops
A WHILE loop is really an IF statement followed by the body of the
loop, followed by an unconditional jump to the top of the loop.
Consider the following example:

while( ax < bx)


ax = ax + 1;

This is a possible implementation:

top:
cmp ax,bx ; check loop condition
jae next ; false? exit loop
inc ax ; body of loop
jmp top ; repeat the loop
next:
Your turn . . .
Implement the following loop, using unsigned 16-bit integers:

while( bx <= val1)


{
bx = bx + 5;
val1 = val1 - 1
}
top:
cmp bx,val1 ; check loop condition
ja next ; false? exit loop
add bx,5 ; body of loop
dec val1
jmp top ; repeat the loop
next:
Example: Write a code to count the number of characters in an input
line. Assembly Code :
Initialize count to 0 MOV DX,0 ; DX counts chars
Read a character MOV AH,1 ; prepare to read
While Char <>carriage return DO INT 21 h ; char in AL
Count=Count+1 WHILE_:
Read a character CMP AL, 0DH ; CR?
END_While JE END_WHILE
INC DX
NOTE: INT 21 H
• because WHILE loop checks JMP WHILE_
terminating condition at top of END_WHILE:
loop , any variable in the
condition , must be initialized
before the loop is entered thus
must read a char , before entering
the loop ,
• The label WHILE_: is used
because WHILE is reserved word
REPEAT LOOP:
The Repeat Loop pseudo algorithm
REPEAT
Statements
Statement
UNTIL Condition
Repeat until loop , the statements
are executed , and then the
condition is checked . If true , the Condition
loop terminate else control False
transfers to the top of the loop.
Thus statement be executed at True
least once
Example: write a code to read characters Until a blank is read

Assembly Code: Pseudo Code


MOV AH,1 ; prepare to read a char REPEAT
REPEAT: Read a character
INT 21 h ; char in AL UNTIL char is blank
CMP AL,” ” ; is it Blank
JNE REPEAT ; no, keep reading a
;char Until Char is
;blank
Branches with compound conditions
Condition_1 AND Condition_2 , called AND condition , or
Condition_1 OR Condition_2 , called OR condition
Where condition_1 and condition_2 are either TRUE or FALSE
1. AND Conditions:
AND condition is True if and only IF condition_1 and condition_2
are both True, otherwise it will be False if one of the condition or
both of them are False.
Example: Read a character , and check it is an uppercase letter
display it.
Pseudo Algorithm:
Read a Character (into AL)
If (char ≥ “A”) AND (char ≤ “Z”) ; if char is A or follows it
Then display it ; if char is Z or preceedes it
END_IF
Assembly Code:
; read a character
MOV Ah,1 ; read a character in AL
INT 21h
; If (char ≥ “A”) AND (char ≤ “Z”)
CMP AL, “A” ; If (char ≥ “A”)
JNGE END_IF ; no, it precedes “A”, Exit
CMP AL, “Z” ; char ≤ “Z”
JNLE END_IF
; then display char
MOV DL,AL
MOV AH,2
INT 21h
END_IF:
Compound Expression with AND
if (al > bl) AND (bl > cl)
X = 1;

This is one possible implementation . . .


cmp al,bl ; first expression...
ja L1
jmp next
L1:
cmp bl,cl ; second expression...
ja L2
jmp next
L2: ; both are true
mov X,1 ; set X to 1
next:
Your turn . . .

Implement the following pseudocode in assembly


language. All values are unsigned:

if( bx <= cx cmp bx,cx


ja next
&& cx > dx )
cmp cx,dx
{ jbe next
ax = 5; mov ax,5
dx = 6; mov dx,6
} next:
Compound Expression with OR
OR condition is True if either Condition_1 or Condition_2 is True or both of
them is True. Its only False when both conditions are false

if (al > bl) OR (bl > cl)


X = 1;

We can use "fall-through" logic to keep the code as short as


possible:

cmp al,bl ; is AL > BL?


ja L1 ; yes
cmp bl,cl ; no: is BL > CL?
jbe next ; no: skip next statement
L1: mov X,1 ; set X to 1
next:
Compound Expression with OR
char n,k; unsigned int w; ;if(n<>k||w<=10)
mov ah,n
if (n<>k || w<=10) cmp ah,k
whatever(); jne then_
• This example uses cmp w,10
short-circuit evaluation ja end_if
› if the first condition is then_:
true it immediately skips call whatever
to the then-part end_if:
Example: Read a character , and if its “y” OR “Y” , display it ; else the
program.
Pseudo Algorithm:
.model small Read a character ( into AL)

.stack 100 h IF ( character=“y”) OR


( character=“Y”)
.code THEN display it
Main proc ELSE terminate the program
Mov Ah,1 End_if
Int 21h
CMP AL,”y” ; IF ( character=“y”) OR ( character=“Y”)
JE THEN
CMP AL , “Y”
JE THEN
JMP ELSE_
THEN: MOV AH,2
MOV DL,AL
INT 21h
ELSE_: MOV AH,4Ch
INT 21h
END_IF
Looping Structures:
A loop is a sequence of instructions that is repeated . The number
of times to repeat may be known in advance or it may depend on
condition

FOR- LOOP:
Initialize
In this loop structure, the loop Count
statements are repeated a known
number of times called
count_controlled loop,
Statement
FOR loop_count DO
Statement;
END_ FOR Count=Count-1
The LOOP is used to implement FOR
loop . The syntax is:
LOOP destination_label
Count=0
The counter for loop is register CX , which is initialized to the value
(loop_count) . Execution of the LOOP instruction cause CX to be
decremented automatically. And if CX ≠ 0 , control transfers to
destination_label .If CX =0, the next transition after LOOP is
executed . The destination_label must precedes the LOOP
instruction by more than 126 bytes as follows :
; initialize CX to loop_count
TOP:
; the body of the loop
LOOP TOP
Example: Write a count-controlled loop to display a raw of 80
asterisks
FOR 80 time DO MOV CX,80 ; number of star to display
Display “*” MOV AH,2
END_FOR MOV DL,”*”
TOP: INT 21 h
LOOP TOP
NOTE : The for LOOP is executed at least once. If CX contain 0
when the loop is entered , then the LOOP instruction cause CX to
be decremented to FFFFh , and the LOOP then executed 65535
more times . To prevent this , the instruction JCXZ (Jump if CX is
zero ) is used before the loop, thus:
Syntax: JCXZ destination _label
Now if CX=0, control transfers to destination_label by passing the
loop, thus:
JCXZ SKIP
TOP:
; body of the loop
LOOP TOP
SKIP:
LOOP
• LOOP destination for (x=9;x>0;x--) n+=x;
› decrements CX but does
not change any flags ;for(x=9;x>0;x--)
› if CX is not zero after mov cx,9
the decrement, control is top_loop:
transferred to the add n,cx ;n=n+x
destination label loop top_loop
› This is a SHORT jump
only
LOOPZ and LOOPE
Syntax:
LOOPE destination
LOOPZ destination
Logic:
› CX  CX – 1
› if CX > 0 and ZF=1, jump to destination
Useful when scanning an array for the first
element that does not match a given value.

In 16-bit real-address mode, CX is the counter,


LOOPZ Example
• This program accepts at mov ah,1
most 9 characters from mov cx,9
next_char:
the keyboard
int 21h
• When the 9th character cmp al,13
is pressed (or the enter loopne next_char
key is used) the number ;determine count
of keypresses is mov ax, 0239h
displayed sub al,cl
mov dl,al
int 21h
LOOPNZ and LOOPNE
• LOOPNZ (LOOPNE) is a conditional loop instruction
• Syntax:
LOOPNZ destination
LOOPNE destination
• Logic:
• CX  CX – 1;
• if CX > 0 and ZF=0, jump to destination
• Useful when scanning an array for the first element
that matches a given value.
; PROGRAM TO CONVERT THE 2-DIGIT HEXADECIMAL NUMBER WHOSE
; ASCII CODES ARE STORED IN THE DX REGISTER (DL=LEAST
; SIGNIFICANT DIGIT, DH=MOST SIGNIFICANT DIGIT) INTO A
; BYTE VALUE IN THE AL REGISTER. THIS PROGRAM IS NOT
; WRITTEN VERY WELL BECAUSE WE HAVEN'T LEARNED ALL OF THE
; INSTRUCTIONS NEEDED TO DO IT WELL.
; FIRST, LET'S PUT SOME CHARACTERS IN DX, SO THE PROGRAM
; WILL HAVE SOME DATA TO WORK ON:
MOV DH,'7'
MOV DL,'F'
; THAT IS, LET'S CONVERT THE NUMBER 7F (HEX).
; THE PROGRAM.
; FIRST, WORK ON THE UPPER DIGIT:
; IF THE DIGIT IS "0"-"9", WE MUST CONVERT IT TO THE
; BYTE 0-9, ELSE IF THE DIGIT IS "A"-"F" WE MUST CONVERT
; IT TO THE BYTE 10-15. THEN, SINCE THIS IS THE MOST
; SIGNIFICANT DIGIT, IT MUST BE MULTIPLIED BY 16 AND STORED.
MOV AL,DH ; GET THE DIGIT
SUB AL,'A' ; IS THE DIGIT BIGGER OR EQUAL TO "A"?
JC NUMERIC_1 ; IF "0"-"9", JUMP TO ANOTHER ROUTINE
ADD AL,10 ; IS "A"-"F", SO CONVERT TO 10-15
JMP CONTINUE_1
; THIS PART IS EXECUTED IF THE DIGIT IS "0"-"9"
NUMERIC_1:
MOV AL,DH ; GET THE DIGIT AGAIN
SUB AL,'0' ; CONVERT TO 0-9
; AT THIS POINT, AL CONTAINS A VALUE 0-15
CONTINUE_1:
ADD AL,AL ; DOUBLE AL
ADD AL,AL ; QUADRUPLE IT
ADD AL,AL ; OCTUPLE IT
ADD AL,AL ; NOW AL CONTAINS 16*UPPER DIGIT OF HEX
; NOW WORK ON THE LOWER DIGIT USING SAME TYPE OF ALGORITHM
MOV AH,DL ; GET THE DIGIT
SUB AH,'A' ; IS THE DIGIT BIGGER OR EQUAL TO "A"?
JC NUMERIC_2 ; IF "0"-"9", JUMP TO ANOTHER ROUTINE
ADD AH,10 ; IS "A"-"F", SO CONVERT TO 10-15
JMP CONTINUE_2
; EXECUTE THIS ONLY IF LOWER DIGIT IS "0"-"9"
NUMERIC_2:
MOV AH,DL ; GET THE DIGIT AGAIN
SUB AH,'0' ; CONVERT TO 0-9
; AT THIS POINT, AH CONTAINS A VALUE 0-15
CONTINUE_2:
ADD AL,AH ; ADD LOWER HEX DIGIT TO 16*UPPER
Problem:
 Prompt for single Hex digit
 '0' through '9', 'A' through 'F', 'a' through 'f'
 Illegal entries must be detected
 Display entry in decimal
 0 through 15
 Ask to repeat the program
 'y' or 'Y' will repeat, anything else exits
Approach :

o The major task is data translation


o Given an ASCII code for a Hex digit, determine the numeric equivalent
(unsigned byte)
o Given an unsigned byte (0-15), display one or two character decimal
representation
o The input/process/output step must be embedded in a do until loop
controlled by the yes/no response of the user
.Model Small
.Stack 100h
.data
input_message db 0Dh,0Ah, 'Enter alegal hex digit: $'
output_message db 0Dh,0Ah,'in decimal this is $'
illegal_message db 'Illegal entry!$'
continue_message db 0Dh,0Ah,'Try again? (Y/N):
$‘
.code
Hexable proc
mov ax,@data ;ax gets segment number
mov ds,ax ;transfer to segment reg
begin_process:
;prompt and accept single char input
lea dx,input_message
mov ah,9 ;display input prompt
int 21h
mov ah,1 ;DOS input function
int 21h ;get single char response
mov bl,al ;for safe keeping
lea dx,output_message
mov ah,9 ;move to new line and get
int 21h ;ready to display result
;convert ASCII hex digit (bl) to unsigned
cmp bl,'9' ;check if decimal digit
jle decimal_size
cmp bl,'F' ;uppercase or lowercase?
jle uppercase
sub bl,'a'-'A' ;lower to uppercase
uppercase: ;handle 'A'-'F' case
sub bl,'A'-10; 'A'-'F' to unsigned
jmp conversion_complete
decimal_size: ;handle '0'-'9' case
sub bl,'0' ;convert to unsigned
conversion_complete:
;verify byte in BL is legal (0-15)
cmp bl,0 ;if <0, illegal
jl illegal
cmp bl,15 ;here if >=0
jle legal ;if also <=15, OK
illegal:
mov ah,9 ;display error message
lea dx,illegal_message
int 21h
jmp begin_process ;start over
legal:
;output byte in BL (0-15) as decimal
mov ah,2 ;DOS output function
cmp bl,10
jl ones_place ;jmp if single digit
mov dl,'1' ;output leading '1'
int 21h
sub bl,10 ;isolate ones place
ones_place:
add bl,'0' ;convert to ASCII
mov dl,bl ;prepare to output
int 21h
begin_process:
;main processing task goes here
lea dx,continue_message
mov ah,9 ;display continue prompt
int 21h
mov ah,1
int 21h ;get response
cmp al,'y' ;y means do again
je begin_process
cmp al,'Y' ;Y means do again
je begin_process
mov ah,4ch ;DOS return, no error
int 21h
hexable endp
end hexable

You might also like