Branch on not equal has the syntax bne rs,rt,label
where the first 6 digits is the opcode, the next 5 digits is the rs, the next 5 digits is the rt and the rest is the label of the branch target address:
BTA = PC + 4 + imm * 4
which is calculated by sign extending the immediate, multiplying by 4 and adding that and 4 to the program counter. For an explaination see this question
How to Calculate Jump Target Address and Branch Target Address?
The bne
format is immediate (I-type). The opcode is 5 (000101). For example, this machine code prints every third character in the alphabet.
00100100000100000000000000110000
00000000000100000010000000100001
00100100000000100000000000001011
00000000000000000000000000001100
00100010000100000000000000000011
00100100000010000000000001011101
00010110000010001111111111111010
00000000000000000000000000000000
00001000000100000000000000001000
00000000000000000000000000000000
It is 10 lines (10 instructions). Line 7 is a branch and it has machine code 00010110000010001111111111111010
. The first 6 numbers 000101
is the opcode 5. Then 5 + 5 bits of registers (in this example the registers are $16 and $8 and the rest is the immediate branch target address.
Similarly, your program
.text
loop:
add $t2,$t2,$t1
addi $t2,$t2,4
sw $t2,4($s0)
bne $t2,20,loop
jr $ra
translates to 7 lines the machine code:
00000001010010010101000000100000
00100001010010100000000000000100
10101110000010100000000000000100
00100000000000010000000000010100
00010100001010101111111111111011
00000011111000000000000000001000
The actual translation looks like this
Address Code Basic Source
0x00400000 0x01495020 add $10,$10,$9 3 add $t2,$t2,$t1
0x00400004 0x214a0004 addi $10,$10,0x00000004 addi $t2,$t2,4
0x00400008 0xae0a0004 sw $10,0x00000004($16)5 sw $t2,4($s0)
0x0040000c 0x20010014 addi $1,$0,0x00000014 6 bne $t2,20,loop
0x00400010 0x142afffb bne $1,$10,0xfffffffb
0x00400014 0x03e00008 jr $31 7 jr $ra
...where the second to last line is the bne
: 00010100001010101111111111111011
. The first 6 digits 000101
is the opcode, the next 5 (00001
) + 5 (01010
) digits are the registers and the rest (1111111111111011
) is the immediate value of the branch target address (in hexadecimal 1111111111111011
=FFFB
.
For more details see a MIPS manual.