if i have two positive integers, say 0x1234 and 0x5678, is 0x8765 + 0xfedc = 0x8641, if the '+' means two's complement addition, mod 2^16?
views:
130answers:
3This question is exceedingly vague. That said:
On the bit level, twos complement addition is equivalent to modular addition of unsigned integers. The only difference is in how you interpret the bit patterns of the inputs and result.
This means that if you have two positive 16-bit twos complement numbers, a and b, then twos_complement_add(a,b) is:
- a + b if (a+b) < 2^15
- a + b - 2^16 otherwise
so what does it mean to add using two's complement? i know to get the two's complement of a number, you flip the bits of a number and add 1 to it.
In the instructions in rc5 say:
Two's complement addition of words, denoted by "+". This is modulo 2^w addition. The inverse operation, subtraction, is denoted "-".
There's no such thing as "two's complement addition of positive numbers" because two's complement is a way of storing negative numbers: -n is stored as ~n + 1, which is equivalent to 2^w - n where w is the width of the integer type.
Two's complement is designed for modulo 2^w arithmetic: (+a) + (-b) is represented as a + (2^w - b) = (a - b) + 2^w, which gives the correct answer of a-b after reduction modulo 2^w. Similarly, (-a) + (-b) is represented as (2^w - a) + (2^w - b) = (-a - b) + 2 * 2^w, which reduces to the expected -a - b.