Assignment Question 1: C to MIPS
i) Convert the following C code into MIPS Assembly using only
lw, sw, add, sub, sll, and srl. Assume array B is stored at the
base address in register $s4.
int k = 3;
int result = 0;
while (k < 8) {
result = result + (k * 1);
B [k -3] = result;
k++;
}
Answer: MIPS Assembly Code :
li $s0, 3
li $s1, 0
li $t2, 8
li $t3, 1
li $t4, 3
loop:
sub $t0, $s0, $t2
beq $t0, $zero, end
add $s1, $s1, $s0
sub $t1, $s0, $t4
sll $t1, $t1, 2
add $t1, $t1, $s4
sw $s1, 0($t1)
add $s0, $s0, $t3
j loop
end:
ii) Explain the benefits of using srl or sll:
Fast multiplication and division by powers of 2
Efficient array indexing by shifting index for byte offset
Improved CPU performance due to single-cycle shift
instructions
Saves instructions by replacing multiply/divide operations
with shifts
Assignment Question 2: Instruction Format Decoding and
Encoding
i) Write the 32-bit binary representation of the following
instructions:
Instruction opcode rs (5 rt (5 rd (5 shamt funct (6 bits)
s (6 bits) bits) bits) bits) (5
bits)
Sub $s1, 000000 01000 0100 0101 0000 100000
$s2, $s3 1 0 0
Instructio Op Base Sourc Offset (16 bit)
n code Addres e
(6 bit) s (5
(5 bit) bit)
Sw $t1, 10101 10000 0100 00000000001000
32($s0) 1 1 00
ii) Decode this instruction:
000000 01000 01001 01010 00000 100000
Instruction type: R-type
Fields of the instruction:
opcode rs (5 rt (5 rd (5 shamt (5 funct (6
(6 bits) bits) bits) bits) bits) bits)
000000 01000 01001 01010 00000 100000
Explanation of each field:
opcode: 000000 means R-type instruction
rs: 01000 = 8 = $t0 (source register 1)
rt: 01001 = 9 = $t1 (source register 2)
rd: 01010 = 10 = $t2 (destination register)
shamt: 00000 means no shift
funct: 100000 = 32 means add operation
Decoded Instruction: add $t2, $t0, $t1