0

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?

1 Answers1

1

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.

Margaret Bloom
  • 41,768
  • 5
  • 78
  • 124
  • How would I be able to print this to the console? – wolverinexci Aug 22 '18 at 08:03
  • @wolverinexci That depends on your execution environment. Both MARS and SPIM have system calls to print numbers. If you are having trouble with it, search this site for possible questions and if none satisfies you, try asking a new one. Since this is not a forum, we don't really engage in a ping-pong of questions and answers, each question must be self-contained as its answer must be. – Margaret Bloom Aug 22 '18 at 08:10
  • I did do a syscall after this. I did li $v0, 4 la $a0, ($a0 ( i guess this is the location of the address)) syscall but I did have an out of range error. – wolverinexci Aug 22 '18 at 08:15
  • 1
    MIPS32r2 added a `seb dst,src` (sign-extend-byte) instruction. See https://godbolt.org/z/D7H2Q3. gcc uses it with `-march=mips32r2`, but otherwise uses left/right shifts like you show. – Peter Cordes Aug 22 '18 at 10:53
  • @PeterCordes Thank you very much! It's a very nice add-on! – Margaret Bloom Aug 22 '18 at 12:38
  • Describing MIPS32r2 as "revision 2 of the ISA" is ambiguous with "MIPS II". The whole MIPS32 / MIPS64 thing didn't happen until 1998 when Silicon Graphics sold off MIPS and the ISA focused on embedded. https://en.wikipedia.org/wiki/MIPS_architecture#MIPS32/MIPS64. – Peter Cordes Aug 22 '18 at 12:53
  • @PeterCordes Yes, I was reading the MIPS history when found this ambiguity and come back to fix it . Thank for your comment anyway :) – Margaret Bloom Aug 22 '18 at 12:57