wolverinexci
wolverinexci

Reputation: 11

How to sign extend a two's complement number given in the program arguments in mips (assembly)

I am trying to sign extend a two's complement number that I get from the program arguments in mips. How would I do this?

Upvotes: 0

Views: 1370

Answers (1)

Margaret Bloom
Margaret Bloom

Reputation: 44058

One way is to take advantage of the MIPS sra instruction, this instruction performs an arithmetic right shift - it shifts right a register while shifting in the sign bit.
By putting the 8-bit value to the far left (read in the most significant position) with a sll we make its sign bit coincide with the register sign bit, then we use sra:

#Assume $a0 is a) 0x40 b) 0x80
sll $a0, $a0, 24      #a) $a0 = 0x40000000 b) $a0 = 0x80000000
sra $a0, $a0, 24      #a) $a0 = 0x00000040 b) $a0 = 0xffffff80

For values in memory, the lb will load a byte sign extending it (contrary to lbu).


Since the release 2 of the MIPS32 ISA, the seb rt, rs instruction that sign-extends the least significant byte of a GP register.

Upvotes: 1

Related Questions