Which arithmetic operations are the same on unsigned and two’s complement signed numbers?

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.

Leave a Comment