Search code examples
binarymipstwos-complementmachine-codeimmediate-operand

How to convert / encode a negative number as an immediate in MIPS machine code


I want to change this instruction to binary or machine code: addi $s3, $s1, -1000.

I know how to encode the opcode, rs, and rt, but I have no idea how to convert -1000 to binary.

I know how to get 1's complement and 2's complement. But i don't know how to express it in this I type instruction.
I just don't know how to express -1000 into last 16 digits as binary number.

since 1000(decimal) is 0000001111101000 in 16 digit.

1's complement is      1111110000010111
                                     +1
=                      1111110000011000 2's complement

so the answer for the whole instruction is

001000 10001 10011 1111110000011000
addi    rs    rt     immediate

Is this right?


Solution

  • Yes, MIPS addi / addiu use a 16-bit signed 2's complement immediate as the low 16 bits of the instruction word. The CPU will sign-extend it to 32 (or 64) bits when decoding.

    But note that ori / xori / andi logical instruction use unsigned 16-bit immediates that are zero-extended to 32-bit (or 64-bit), so -1000 is not encodable.

    To implement xori $t0, $t1, -1000, you'd need to create a 32-bit -1000 in a register with something like addiu $at, $zero, -1000, then you could xori $t0, $t1, $at. ($at is the "assembler temporary" register that pseudo-instructions like bgt use.)