Puzzle: Two's Complement Arithmetic
The following table describes a set of functions that make use of
the two's complement representation of integers. Again, refer to the
notes below and the comments in bits.c.
| Name | Description | Rating | Max Ops |
|---|---|---|---|
tmax(void) |
largest two's complement integer | 1 | 4 |
isNonNegative(x) |
x >= 0? |
3 | 6 |
isGreater(x,y) |
x > y? |
3 | 24 |
divpwr2(x,n) |
x/(1 << n) |
2 | 15 |
abs(x) |
absolute value | 4 | 10 |
addOK(x,y) |
Does x + y overflow? |
3 | 20 |
Arithmetic Functions
-
tmaxreturns the largest integer. -
isNonNegativedetermines whetherxis less than or equal to 0. -
isGreaterdetermines whetherxis greater thany. -
divpwr2divides its first argument by \( 2^n \), where \( n \) is the second argument. You may assume that \( 0 \leq n \leq 30 \). It must round toward zero. -
absis equivalent to the expressionx < 0 ? -x : x, giving the absolute value ofxfor all values other than \( TMin \). -
addOKdetermines whether its two arguments can be added together without overflow.
Testing Your Solutions
Use the same btest program described in the previous section to test
your solutions to these puzzles as you work on them. Again, use the
make command to build the btest program after each change to your
bits.c file, and then run ./btest to see which tests pass and which
fail.
You can also use the dlc tool described in the previous section to
check that your solutions follow the coding rules.
(When logged in, completion status appears here.)