15 less than and greater than comparison (cjne) – Texas Instruments MSC1210 User Manual
Page 211
Less Than and Greater Than Comparison (CJNE)
16-17
8052 Assembly Language
Code structures similar to the one shown previously are very common in 8052
assembly language programs to execute certain code or subroutines based
on the value of some register, in this case the accumulator.
16.15 Less Than and Greater Than Comparison (CJNE)
Often it is necessary not to check whether a register is or is not certain value,
but rather to determine whether a register is greater than or less than another
register or value. As it turns out, the CJNE instruction—in combination with the
carry flag—allows us to accomplish this.
When the CJNE instruction is executed, not only does it compare parameter1
to parameter2 and branch if they are not equal, but it also sets or clears the
carry bit based on which parameter is greater or less than the other.
-
If parameter1 < parameter2, the carry bit will be set to 1.
-
If parameter1
≥
parameter2, the carry bit will be cleared to 0.
This is the way an assembly language program can do a greater than/less than
comparisons. For example, if the accumulator holds some number and we
want to know if it is less than or greater than 40
H
, the following code could be
used:
CJNE A,#40h,CHECK_LESS
;If A is not 40h, check if < or > 40h
LJMP A_IS_EQUAL
;If A is 40h, jump to A_IS_EQUAL code
CHECK_LESS:
JC A_IS_LESS
;If carry is set, A is less than 40h
A_IS_GREATER: {Code}
;Otherwise,
it
means
A
is
greater
than
40h
The code above first compares the accumulator to 40
H
. If they are the same,
the program falls through to the next line and jumps to A_IS_EQUAL because
we already know they are equal. If they are not the same, execution will contin-
ue at CHECK_LESS. If the carry bit is set, it means that the accumulator was
less than the second parameter (40
H
), so we jump to A_IS_LESS, which will
handle the less than condition. If the carry bit was not set, execution falls
through to A_IS_GREATER, at which point the code for the greater than condi-
tion would be inserted.
Note:
Keep in mind that CJNE will clear the carry bit if parameter1 is greater than
or equal to parameter2. That means it is very important that the values are
checked to be equal before using the carry bit to determine less than/greater
than. Otherwise, the code might branch to the greater than condition when,
in fact, the two parameters are equal.