Skip to main content

Exercises 2.10 Programming Exercises

2.

Using the program in Listing 2.9.2, how many bits are in the largest unsigned integer that is supported by this program?

Hint

How many \(\hex{f}\)s will be accepted when the program prompts for a hexadecimal value?

Answer

You can type as many \(\hex{f}\)s as you like, but the program only accepts eight. Therefore, the largest unsigned integer is \(4 \times 8 = 32\) bits.

3.

Modify the last printf statement in the program in Listing 2.9.2 so that the hexadecimal value is displayed in signed integer format. What is the largest integer you can enter in hexadecimal while still getting “correct” output?

Solution
printf("%#010x represents the unsigned decimal integer %d\n",
          bitPattern, bitPattern);

Any integer greater than \(\hex{7fffffff}\) gives a negative output. This will be explained in Section 3.4, but for now realize that this change is caused by printf formatting, not the storage format, which is still unsigned int. Also note that we did not change scanf's reading format.

4.

Modify the program in Listing 2.9.2 so that it also displays the addresses of the x and y variables. The addresses should be displayed in hexadecimal. How many bytes does the compiler allocate for each of the ints?

Hint

The printf formatting code to display an address is %p.

Solution
/* echoDecHexAddr.c
 * Prompts user to enter a number in decimal, another in
 * hexadecimal then echoes both in both bases, also showing
 * where values are stored.
 * 2017-09-29: Bob Plantz
 */

#include <stdio.h>

int main(void)
{
  int x;
  unsigned int y;

  while(1)           // loop "forever"
  {
    printf("Enter a decimal integer (0 to quit): ");
    scanf("%i", &x);
    if (x == 0) break;        // break out of loop

    printf("Enter a bit pattern in hexadecimal: ");
    scanf("%x", &y);
    if (y == 0) break;        // break out of loop

    printf("%i is stored as %#010x at %p, and\n", x, x, &x);
    printf("%#010x represents the decimal integer %d stored at %p\n\n",
	          y, y, &y);
  }
  printf("End of program.\n");

  return 0;
}

Notice the use of an “infinite” loop and a break statement to end a program.