ANSWERS TO NUMBER REPRESENTATION EXERCISES




 1. First convert to binary: 7654 = 111 110 101 100 = 1111 1010 1100 = FAC


 2. 7*8^3 + 6*8^2 + 5*8 + 4 = 7*512 + 6*64 + 40 + 4 = 4012


 3. 7654 decimal is 16746 octal
    8^4 = 4096  7654 - 1*4096 = 3558
    8^3 =  512  3558 - 6*512  =  486
    8^2 =   64   486 - 7*64   =   38
    8^1 =    8    38 - 4*8    =    6
    8^0 =    1     6 - 6*1    =    0


 4. Shortcut: convert the octal from exercise 3 to binary (see exercise 1).
    1110111100110


 5.       #include <stdio.h>
          int main(void) {
             int n;
             scanf("%d", &n);
             printf("%o\n", n);
             return 0;
          }


 6.       #include <stdio.h>
          int main(void) {
             int n;
             scanf("%o", &n);
             printf("%d\n", n);
             return 0;
          }


 7.       #include <stdio.h>
          int main(void) {
             float x, y;
             scanf("%f %f", &x, &y);
             printf("%.2f\n", x / y);
             return 0;
          }



 8.       #include <stdio.h>
          int main(void) {
             double x, y;
             scanf("%lf %lf", &x, &y);
             printf("%.2f\n", x / y);
             return 0;
          }



 9.       #include <stdio.h>
          int main(void) {
             int x, y;
             scanf("%d %d", &x, &y);
             printf("%.2f\n", (double) x / y);
             return 0;
          }

    Note: the cast is needed to prevent integer division. Casting has
    higher precedence than division so x is promoted to a double
    before the division.  An alternative is 1.0 * x / y.

10. The number of bits in the binary representation of a positive
    integer n is the smallest integer greater than or equal to log_2 (n+1).
   
           int f(int n) {  
              int i = 1, log2i = 0;
              while (i < n + 1) {
                 i += i;
                 log2i++;
              }
              return log2i;
           }

11. The following results were obtained on arizona.

          yuma.Princeton.EDU% gcc floating-point.c
          yuma.Princeton.EDU% a.out
          x != 0.3

     This may come as quite a surprise, but floating point
     numbers are not represented exactly in C (nor in most
     other programming languages). Testing for exact equality
     is usually a bad idea.