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

▼魔方 西西 提交于 2019-11-26 16:48:13

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!