Question

I'm designing a simple toy instruction set and accompanying emulator, and I'm trying to figure out what instructions to support. In the way of arithmetic, I currently have unsigned add, subtract, multiply, and divide. However, I can't seem to find a definitive answer to the following question: Which of the arithmetic operators need signed versions, and for which are the unsigned and two's complement signed versions equivalent?

So, for example, 1111 in two's complement is equal to -1. If you add 1 to it and pretend that it's an unsigned number , you get 0000, which is correct even when thinking of it as -1. However, does that hold for all numbers? And what about for the other three operations (subtraction, multiplication, division)?

Était-ce utile?

La solution 2

Add and subtract are the same for signed and unsigned 2s complement, assuming you're going to handle overflow/underflow in the normal way for most CPUs, i.e. just wrap around. Multiply and divide are different. So you only need one addition routine and one subtraction routine regardless of signedness, but you need separate signed and unsigned multiply and divide.

Autres conseils

Addition, subtraction and multiplication are the same provided:

  1. Your inputs and outputs are the same size
  2. Your behaviour on overflow is wraparound modulo 2n

Division is different.

Many instruction sets offer multiplication operations where the output is larger than the input, again these are different for signed and unsigned.

Furthermore if you are writing your emulator in C there are some misfeatures of the language that you need to be aware of.

  1. Overflow of signed arithmetic in C is undefined behaviour. To get reliable modulo 2n behaviour arithmetic must be performed using unsigned types.
  2. C will promote types smaller than int to int. Great care is needed to avoid such promotions (adding 0u or multiplying by 1u at the start of your calculation is one way).
  3. Conversion from unsigned types to signed types is implementation defined, the implementations i've seen do the sensible thing but there may be some that don't.

All your operations need overflow checks, or they will return incorrect values in some cases. The unsigned versions of these checks are different from the signed ones, so you'll need to implement each routine separately.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top