itoa for negative numbers?

assembly, mips

Solution

You can include this in your code, right above `itoa_div_begin`:

li t0, 0x40000000
and t0, a0, t0
beqz t0, itoa_div_begin
nop
li t0, 45
sb t0, 0(a1)
addi a1, a1, 1
not a0, a0
addi a0, a0, 1

itoa_div_begin:

What is does:

- Check for a negative number by checking if the MSB is 1

- If so, insert `-` in result, and

- Use the two's complement of the number for the rest of the function

Problem

Bounty: +50 reputation points for anyone that provides the code to make this subroutine work with negative numbers. I wrote a MIPS program to convert Fahrenheit to Celsius. It opens its own output window (i.e. UART) and properly displays the value in Celsius. It does all of this while making calls from C to assembly and vice versa. Entire code posted below. I am struggling with getting it to work with negative numbers. Just drawing a blank right now for some reason. How do I change my `itoa` function to write this check? Anyone have any ideas how to get this working with negative values in MIPS? ``` .ent itoa itoa: // putting the stack frame together addiu sp, sp, -16 sw fp, 12(sp) move fp, sp sw a0, 16(fp) sw a1, 20(fp) sw s0, 4(fp) sw s1, 0(sp) // there is no divide immediate, so using s1 li s1, 10 itoa_div_begin: divu a0, s1 mfhi s0 mflo a0 addiu s0, s0, 0x30 addiu sp, sp, -1 sb s0, 0(sp) beq a0, zero, itoa_div_done nop j itoa_div_begin nop itoa_div_done: itoa_copy_begin: lb s0, 0(sp) sb s0, 0(a1) addiu sp, sp, 1 subu s1, sp, fp addiu a1, a1, 1 beq s1, zero, itoa_copy_done nop j itoa_copy_begin nop itoa_copy_done: li s0, 0 sb s0, 0(a1) move v0, a1 lw a0, 16(fp) lw a1, 20(fp) lw s0, 4(fp) lw s1, 0(fp) // stack frame move sp, fp lw fp, 12(sp) addiu sp, sp, 16 jr ra nop .end itoa ```

Original source