Reference: Compare

A number comparison routine is a nice LEAF function in assembly language.

Requirements:

  • X and Y Values are signed 32 bit Integer
    • Passed in registers a0 and a1 respectively
  • Result value placed in v0
  • Result value calculation is:
    • -1 = x < y
    • 0 = x == y
    • 1 = x > y

In C the following function would accomplish the task.

int compare_int(int x, int y)

{

if (x < y)

return -1;

if (x == y)

return 0;

// if (x > y) Assumed

return 1;

}

The MIPS assembly code

compare_int:

beql a0, a1, compare_int_complete

add v0, r0, r0

slt v0, a1, a0 // a0 - a1 = tmp0 a0

beql v0, r0, compare_int_complete

addi v0, r0, -1

compare_int_complete: