I have an assignment where I have to convert MIPS instructions into its hexadecimal machine code. I know how to convert the add, addi, lw, etc. instructions just fine, but when it gets to instructions like beq, I get confused. How would I convert this beq to hex?
0x00400108 beq $t3, $t5, NEXT
0x0040010C j END
where the address of NEXT is
0x0040011C
?
What I've tried:
beq opcode = 4
$t3 = register 11
$t5 = register 13
NEXT = 0x0040011C - 0x0040010C = 10 (hex) = 16 (decimal)
4 11 13 16 (decimal)
000100 01011 01101 0000 0000 0000 1000 (convert to binary)
0001 0001 0110 1101 0000 0000 0000 1000 (group into fours)
1 1 6 D 0 0 0 8 (hexadecimal)
but it's wrong...
After spending a long time being dumb, I've found the correct answer.
The summarized code:
beq $t3, $t5, NEXT
[instruction 1]
[instruction 2]
[instruction 3]
[instruction 4]
NEXT: [instruction 5]
As Michael said, the offset is the number of words from the instruction following the branch instruction. Instruction 1 is the following instruction after beq, so start counting from there till NEXT. There are 4 instructions from instruction 1 and NEXT, so the format for beq is now:
op | rs | rd | 16-bit constant or address
000100 | 01011 | 01101 | 0000 0000 0001 0000
Where rs is $t3 and rd is $t5.
Regrouped and converted into hex:
0001 | 0001 | 0110 | 1101 | 0000 0000 0001 0000
1 | 1 | 6 | D | 0 0 1 0
So the hexadecimal representation is 116D0010. Cheers.
Edit:Instructions are Words, 4 Instructions * 4 Bytes = 16 bytes