Sunday, March 8, 2020

Absolute value through shift and xor in MIPS

This is a sample MIPS assembler code to get the absolute value of an integer number using the sra and xor instructions. Full explanation in the comments.

Launch EzMIPS, copy the following MIPS code and paste it into EzMIPS. Assemble, Run.


# ------------ absolute value through shift and xor -------------- #

.data
szPrompt:  .asciiz "Enter integer : "
szMessage: .asciiz "Absolute value: "

# ---------------------------------------------------------------- #

.text

main:

# ...................... print "Enter num: " ..................... #

    li $v0, 4              # print string code = 4
    la $a0, szPrompt       # load address of szPrompt in $a0
    syscall                # print it!

# ................................................................ #

    li $v0, 5              # Read integer
    syscall                # read num into $v0
    move $t1, $v0          # Save number in $t1

# ................................................................ #
    sra $t2, $t1, 31
    # if $t1 is positive $t2 will be set to 0,
    # and if $t1 is negative $t2 will be set to 0xFFFFFFFF.

    xor $t3, $t2, $t1
    # each bit of $t2 is EITHER inverted if $t1 is 0xFFFFFFFF, 
    # OR left unchanged if $t1 is 0.

    # Note: Inverting all bits of a number is the same as setting
    # it to (-number)-1 (in two's complement).


    sub $t4, $t3, $t2
    # EITHER 0xFFFFFFFF (which equals -1) OR 0 is subtracted
    # from the intermediate result => The absolute value 

# ................... print "\nThe absolute value is " ........... #

    li $v0, 4              # # print string code = 4
    la $a0, szMessage      # load address of szMessage
    syscall                # print it!

# ................................................................ #

    li $v0, 1              # print integer
    move $a0, $t4          # absolute value is held by $t4
    syscall

# ....................... exit the program ....................... #

    li $v0, 10
    syscall

# ---------------------------------------------------------------- #


Please let me know of any suggestions or bugs regarding the code above.

Regards,

Antonis

No comments:

Post a Comment