Integer Arithmetic
Unsigned Addition
Given , the result of truncating the integer sum
to be
bits long and then viewing the result as an unsigned number.

modular arithmetic: compute the sum modulo
by simply discarding any bits with weight greater than
in the bit-level representation of
.
We can characterize operation as follows:
Note:
When , the leading bit in the
#card=math&code=%28w%2B1%29&height=18&width=48) bits representation of the sum will equal
, and hence discarding it will not change the numeric value. On the other hand, if
, the leading bit in the
#card=math&code=%28w%2B1%29&height=18&width=48) bits representation of the sum will equal
, and hence discarding it is equivalent to subtracting
from the sum.

Two’s Complement Addition
With two’s complement addition, we must decide what to do when the result is
either too large (positive) or too small (negative) to represent.
Given integer values and
in the range
, their sum is in the range
, potentially requiring
bits to represent exactly.


Two’s Complement Negation
Note:
Observing that . This would cause negative overflow, and
. For value of
such that
, the value
can therefore be represented by
bits two’s complement number, and their sum will be
.
Unsigned Multiplication
Integers and
in the range
can be represented as
bits unsigned numbers, but their product
can range between
and
%5E2%3D2%5E%7B2w%7D-2%5E%7Bw%2B1%7D%20%2B1#card=math&code=%282%5Ew%20-1%29%5E2%3D2%5E%7B2w%7D-2%5E%7Bw%2B1%7D%20%2B1&height=20&width=177). This could require as many as
bits to represent.
Two’s Complement Multiplication
Integers and
in the range
can be represented as
bits two’s complement numbers, but their product
can range between
%3D-2%5E%7B2w-2%7D%2B2%5E%7Bw-1%7D#card=math&code=-2%5E%7Bw-1%7D%5Ccdot%20%282%5E%7Bw-1%7D-1%29%3D-2%5E%7B2w-2%7D%2B2%5E%7Bw-1%7D&height=20&width=234). This could require as many as
bits to represent in two’s complement form.
Note:
When multiplying by a power of 2, one important optimization used by compilers is to combine shift and addition operations.
This property can be derived using:
%3D%5Csum%7Bi%3D0%7D%5E%7Bw-1%7Dx_i%202%5E%7Bi%2Bk%7D%3Dx%202%5Ek%0A#card=math&code=B2U%7Bw%2Bk%7D%28%5Bx%7Bw-1%7D%2Cx%7Bw-2%7D%2C…%2Cx0%2C0%2C…%2C0%5D%29%3D%5Csum%7Bi%3D0%7D%5E%7Bw-1%7Dx_i%202%5E%7Bi%2Bk%7D%3Dx%202%5Ek%0A&height=47&width=371)
Also, dividing by a power of 2 can also be performed using shift operations. This time we use a right shift rather than a left shift.
Why Should I Use Unsigned?
Don’t use without understanding implications
Easy to make mistakes
unsigned i;for (i = cnt-2; i >= 0; i--)a[i] += a[i+1];
Can be very subtle
#define DELTA sizeof(int) int i; for (i = CNT; i-DELTA >= 0; i-= DELTA) . . .
