I'm currently studying MIPS assembly code, and I'm having trouble understanding the solution for question (b) of a particular problem. I was hoping someone could help me clarify a specific part of the solution.

Here's the problem and the given solution:

(b) Consider the following MIPS assembly code.

addi $t3, $zero, 220
addi $t3, $t3, -2
add $s3, $s3, $s1
bne $t3, $zero, repeat

Write down the machine code for the bne instruction given in the code above. Answer as a 32-bit hexadecimal number.


(b) Short answer: 0x1560fffd
Elaborated answer: The bne instruction is an I-type instruction. The immediate field encodes the relative address that the branch instruction should jump to. According to the MIPS reference sheet, the branch target address is computed as follows:

BTA = PC + 4 + signext(imm) * 4

If we assume that the bne instruction is located at address X, then the BTA must be equal to X - 8. Hence, we have the equation:
X - 8 = X + 4 + signext(imm) * 4

which is the same as:
signext(imm) = -3

Consequently, by computing the two’s complement number of -3 and sign extending it to a 16-bit hexadecimal number, we get 0xfffd.

The part I'm struggling to understand is why we write the equation as "X - 8 = X + 4 + signext(imm) * 4"? I asked ChatGPT and was told "X - 8 = X + 4 + signext(imm) * 4 arises from the relationship between the branch target address (BTA), the program counter (PC), the immediate value (imm), and the assumption of the branch instruction's location at address X" but it's still vague.

Could someone kindly explain why we subtract 8 from X and add 4 to the equation?


1 Answer 1


X is the PC at the time of the bne, and the repeat label in this snippet is two 32-bit instructions (ie 8 bytes) before it. As the AI said, the + 4 is from the equation in the reference manual, presumably because the PC has already been advanced by one instruction by the time the branch is taken (I have confirmed this +4 is in the manual, always check what AI tells you it lies very often).

I believe MIPS even has a branch-delay slot (I've not studied it for over twenty years), so it probably even executes the instruction at PC+4 before branching!

In effect you are jumping back three instructions, two in the code and that extra +4, so you need a jump of -3 instructions. Then twos-complement it, shift it two bits to the right and you have the immediate part of the opcode specified in the answer.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.