maddie
maddie

Reputation: 1954

MIPS Instructions on signed bits

I multiplied two numbers(one negative, and one positive) in MIPS and when I printed the value to the console, it correctly interpreted it as a negative integer. However, after I did this instruction:

andi $t3, $t3, 255 

(I did this to access only the first 8 bits)

The value printed to my console was positive. Is there a way to maintain the signed value of a binary number through various instructions/operations in MIPS?

Upvotes: 0

Views: 2642

Answers (1)

Craig Estey
Craig Estey

Reputation: 33631

No, not in this way (i.e. anding).

A negative number has the MSB set (i.e. 0x80000000). When you do the andi, you lose this bit (i.e. destroy it).

Consider -1, which is 0xFFFFFFFF. When you and against 255 (0x000000FF), you get 0x000000FF, which is 255 decimal.

Consider -2, which is 0xFFFFFFFE. When you and against 255 (0x000000FF), you get 0x000000FE, which is 254 decimal.

If you had a signed char [as in C], the range is -128 (0x80) to 127 (0x7F).

You could sign extend this with:

    sll     $t3,$t3,24              # force sign bit of byte into sign of word
    sra     $t3,$t3,24              # sign extend the register

But, this only works for the range of the signed char value. For example, if you originally had 511 (0x000001FF) and did this, you'll end up with -1, which is incorrect.

So, really, doing the andi invalidates the question, so to speak.

You can retain the original signedness by preserving the original value, in parallel, and doing something with it later.

Upvotes: 0

Related Questions