Lecture 19 GetBits Solution

Joseph Haugh

University of New Mexico

getbits.c: headers, constants, globals

#define MAX_UINT_VAL 4294967295L
#define MAX_BITS 31

/* Error codes */
#define X_RANGE 1
#define P_RANGE 2
#define N_RANGE 4
#define TOO_MANY_BITS 8
#define UNKNOWN 16

int error = 0;
int done = 0;

getbits.c: getbits

unsigned getbits(unsigned x, int p, int n) {
  return (x >>(p+1-n)) & ~(~0 << n);
}

getbits.c: readInt

unsigned int readInt(long max, int errCode) { 
  long num = 0;
  int c = getchar();
  while (c != ':' && c != '\n' && c != EOF) { 
    if (error == 0) { 
        if (c >= '0' && c <= '9') { 
            num = num * 10 + c -'0';     
          if (num > max) error |= errCode;
        }
        else error |= UNKNOWN;   
    }
    c = getchar();       
  }
  if (c == EOF) done = 1;
  return (unsigned int) num;
}

getbits.c: printError

void printError() {
  printf("Error: ");

  if(error & X_RANGE) printf("value out of range");
  else if(error & P_RANGE) { 
    printf("position out of range");
  }
  else if(error & N_RANGE) { 
    printf("number of bits out of range");
  }
  else if(error & TOO_MANY_BITS) { 
    printf("too many bits requested from position");
  }
  else printf("Unknown error");

  printf("\n");
}

getbits.c: main

int main(void) { 
  unsigned int x;
  int p,n;
  while (!done) { 
    x = readInt(MAX_UINT_VAL, X_RANGE);
    p = (int)readInt(MAX_BITS, P_RANGE);
    n = (int)readInt(MAX_BITS, N_RANGE);
    if (done) break;
    if (n > p+1) error |= TOO_MANY_BITS;
    if (error) printError();
    else { 
      printf("getbits(x=%u, p=%d, n=%d) = %u\n", 
             x, p, n, getbits(x,p,n));
    }
    error=0;
  }
  return 0;
}