CS 105

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

  • tmax returns the largest integer.

  • isNonNegative determines whether x is less than or equal to 0.

  • isGreater determines whether x is greater than y.

  • divpwr2 divides 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.

  • abs is equivalent to the expression x < 0 ? -x : x, giving the absolute value of x for all values other than \( TMin \).

  • addOK determines 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.

To Complete This Part of the Assignment

You'll know you're done with this part of the assignment when you've done all of the following:

(When logged in, completion status appears here.)