Question

So I'm hoping to get a little guidance on this one. I have a function that takes a radix(base) and then using getchar() will get the number to convert from the given radix to an integer representation.

The only argument given is the radix number, then getchar() gets the number representation via the command line.

So if I pass

str2int 16
input a number: 3c

It should output (16^1*3) + (16^0*12) = 48 + 12 = 60.

I fully understand the math, and different ways of converting bases, but don't know how to go about coding something up. The math is always MUCH easier than the code, at least to me.

Another way to compute would be: (702) base 15 = 15*7 + 0 = 105; 15*105 + 2 = 1577

I don't know how to express this in C only using getchar()? Is it possible to do without using the math function?

Was it helpful?

Solution

Keep getting one char at a time until not a digit or no more are needed.

unsigned shparkison(unsigned base) {
  unsigned sum = 0;
  int ch;
  while ((ch = getchar()) != EOF) {
    // one could instead look up the toupper(value) in an array "0123...ABC...Z"; 
    // Following assumes ASCII
    if (isdigit(ch)) ch -= '0';
    else if (islower(ch)) ch -= 'A' - 10;
    else if (isupper(ch)) ch -= 'a' - 10;
    else {
      break; // Not a digit
    }
    if (ch >= base) {
      break; // Digit too high
    }
    unsigned sum_old = sum;
    sum *= base;
    sum += ch;
    if (sum < sum_old) {
      sum = sum_old;
      break; // Overflow
    }
  }
  ungetc(ch, stdin);
  return sum;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top