I am confused about the difference between add and addu.
The MIPS instruction reference says:
My understanding is to use add with signed operands and addu with unsigned operands.
But let's consider this example (with only 6bit):
overflow | V 1 | 1 1 1 <- carry | 1 1 1 1 0 1 + | 1 1 1 1 1 0 = ----------------- | 1 1 1 0 1 1
And this is my reasoning:
Now my questions are:
In MIPS, what is the difference between the add and addu instructions? add causes an exception (stops normal execution of the program and goes to the exception handler or aborts) if the result of the addition causes an overflow. addu does not cause an exception if the result of the addition causes an overflow.
The addu instruction performs the Binary Addition Algorithm on the contents of two 32-bit registers and places the result in the destination register.
Despite its name, add immediate unsigned ( addiu ) is used to add constants to signed integers when we don't care about overflow. MIPS has no subtract immediate instruction, and negative numbers need sign extension, so the MIPS architects decided to sign-extend the immediate field.
1 Answer. Show activity on this post. Like all machine instructions, subu will give you a binary result -- 32 bits that are stored in the destination register. These bits are just bits, they are neither positive or negative in and of themselves, it depends on how you interpret them.
The instruction names are misleading. Use addu
for both signed and unsigned operands, if you do not want a trap on overflow.
Use add
if you need a trap on overflow for some reason. Most languages do not want a trap on signed overflow, so add
is rarely useful.
If you are using signed numbers, you should use add
if you want a trap to be generated when the result overflows.
If you are using unsigned numbers, you should always use addu
and check the overflow of the addition by comparing the result with either numbers (if the result is less than the operands then the addition did overflow).
Here goes a snippet to show how you would check for overflow in unsigned addition:
li $a1, 0xFFFF0FFF
li $a2, 0x00010000
addu $a3, $a1, $a2 # This unsigned addition overflows (set $a3 to $a1+$a2)
bgt $a1, $a3, overflowed
bgt $a1, $a2, overflowed
# If you get here, unsigned addition did not overflow
# your code goes here...
overflowed:
# If you get here, unsigned addition overflowed
# your code goes here...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With