Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
775 views
in Technique[技术] by (71.8m points)

mips - Difference between add and addu

I am confused about the difference between add and addu.

The MIPS instruction reference says:

  • add (with overflow)
  • add unsigned (no overflow)

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:

  • if I consider the first and second operand signed numbers (two's complement), then the result is correct (-3 + -2 = -5) and I don't want an overflow exception. So I would use addu to avoid this exception, but, although the result is the same, the name suggests to use addu is for unsigned numbers!
  • if I consider the first and second operand unsigned numbers, then I want an exception to be raised (because 61 + 62 is not equal to 59). So I would use add to raise the exception, and not addu, as the name would suggest to do.

Now my questions are:

  • assuming that operands are signed (negative in the example above) numbers, should I use addu (as my reasoning suggests) or I should use add (as the name suggests)?
  • assuming that operands are unsigned (positive) numbers, should I use add (as my reasoning suggests) or addu (as the name suggests)?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...