4
votes

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...

2
The offset stored in the instruction is in number of words (32-bit entities) from the instruction following the branch instruction. Refer to a MIPS instruction set reference.Michael
I tried, but I don't really understand it. Do you mean I count the number of instructions between bne and NEXT, and multiply that by 4 since it's 32-bits? :(Aitalas

2 Answers

6
votes

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

0
votes

Since the instructions have a offset of 3 commands from where the pc put in 3 and not 4 into the offset. Thus the binary rep is 0001 | 0001 | 0110 | 1101 | 0000 0000 0000 0011 and not what the edited answer says about multiplying by 4.

Check out the example in this pdf: https://ai.berkeley.edu/~cs61c/sp17/lec/11/lec11.pdf