Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Greater than, less than equal, greater than equal in MIPS

Tags:

assembly

mips

Given two registers $s0, $s1, how can I convert the following pseudocode into MIPS assembly language using only the slt (set on less than) and beq and bne (branch if equal, branch if not equal) instructions.

   if ($s0 > $s1) { goto label1 }
   if ($s0 >= $s1) { goto label2 }
   if ($s0 <= $s1) { go to label3 }
like image 943
jaynp Avatar asked Mar 03 '13 07:03

jaynp


People also ask

How do you know if two numbers are equal in MIPS?

You can check that the first register isn't smaller than the second, and the second isn't smaller than the first, so it means they are equals...

What is BLTZ in MIPS?

Branch on Less than Zero, Branch on Greater than Zero.


Video Answer


2 Answers

I'm assuming that the pseudocode executes sequentially, so an earlier condition being true means you go there and never reach the later if statements. This makes the last branch guaranteed taken if it's reached at all, so it doesn't even need to be conditional. (Also assuming that this is a MIPS without a branch-delay slot.)

slt  $t1,$s1,$s0      # checks if $s0 > $s1
bne  $t1,$zero,label1 # if $s0 >  $s1, goes to label1
beq  $s1,$s2,label2   # if $s0 == $s2, goes to label2 
# beq  $t1,$zero,label3 # if $s0 <  $s1, goes to label3
b    label3            # only possibility left

If that's not the case, you'll want to implement $s0 >= $s1 as
!($s0 < $s1) with slt $t1, $s0, $s1 / beqz $t1, target, for example,
as shown in Ahmed's answer.

like image 102
glew Avatar answered Sep 30 '22 17:09

glew


To implement each compare separately, without optimizing across multiple compares with earlier true conditions making later ones unreachable:

slt $at, $s1, $s0           # $s0 > $s1  as ($s1 < $s0) != 0
bne $at, $zero, label1

slt $t0, $s0, $s1           # $s0 >= $s1 as (s0<s1) == 0
beq $t0, $zero, label2

slt $t1, $s1, $s0           # $s0 <= $s1 the same but reversing the inputs
beq $t1, $zero, label3

label1:
label2:
label3:

Related:

  • How to do less than or equal in Assembly Language(MIPS)? - branchless compare-into-register for things like C return (z<=y); as an int.
like image 20
Ahmed Ehab Avatar answered Sep 30 '22 16:09

Ahmed Ehab