Search code examples
assemblymipsabsolute-value

Integer absolute value in MIPS?


Do you have any simple ways to make a value in a register in MIPS as an absolute value?


Solution

  • Here is a pretty simple way to do it.

    #assume you want the absolute value of r1
            ori $2, $zero, $1      #copy r1 into r2
            slt $3, $1, $zero      #is value < 0 ?
            beq $3, $zero, foobar  #if r1 is positive, skip next inst
            sub $2, $zero, $1      #r2 = 0 - r1
    foobar:
    #r2 now contains the absolute value of r1