简体   繁体   中英

convert this C++ code to MIPS?

I have a problem where I am supposed to write an if-else in MIPS. The problem is originally written in C++ and I have to convert it. Please help if anyone can. I specifically need to know how to set up the switch statements in mips

PROBLEM:

  • if x has a value if 2, print "bbb"
  • if x has a value of 3, print "ccc"
  • if x has a value of 4, print "ddd"
  • if x has a value other than 2, 3, or 4 print "eee"
result = "";

switch (x)
{  
    case 2: result = result + "bbb"; break;    
    case 3: result = result + "ccc"; break;
    case 4: result = result + "ddd"; break;
    default: result = result + "eee";
}

cout << "3.\t" << result << endl;

Switch in MIPS could be implemented in the following way:

    # register to be switched is in $s0
switch:
    addi $t0, $zero, 2
    bne $s0, $t0, case3
    # write code for case 2 here
case3:
    addi $t0, $zero, 3
    bne $s0, $t0, case4
    # write code for case 3 here
case4:
    addi $t0, $zero, 4
    bne $s0, $t0, default
    # write code for case 4 here
default:
    # write default code here

Also refer to the widely used MIPS Green Card , which I'm sure can help you with other difficulties you might face along the way.

.data
msg2: asciiz "bbb"
msg3: asciiz "ccc"
msg4: asciiz "ddd"
def: asciiz "eee"
.text
main:
#get x
li $v0,5
syscall
move $t1,$v0
#x in t1
addi $t0, $zero, 2
beq $t0,$t1,printb
addi $t0, $zero, 3
beq $t0,$t1,printc
addi $t0, $zero, 4
beq $t0,$t1,printd
#if we have come this far and not branched else where means $t0 has value 
4 and didnt went to printd branch print eee
li $v0,4
la $a0,default
syscall
#end this function
li $v0,10
syscall
printb:
li $v0,4
la $a0,msg2
syscall
printc:
li $v0,4
la $a0,msg3
syscall

printd:
li $v0,4
la $a0,msg4
syscall

in data msgs are defined then take an input comparing from up to down. if reached till the end means it didnot went to any branch just execute default case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM