Which arithmetic operations are the same on unsigned and two's complement signed numbers?
Solution 1:
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.
Solution 2:
Addition, subtraction and multiplication are the same provided:
- Your inputs and outputs are the same size
- 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.
- Overflow of signed arithmetic in C is undefined behaviour. To get reliable modulo 2n behaviour arithmetic must be performed using unsigned types.
- 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).
- 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.