1

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?

4

1 回答 1

0

继续一次获得一个char,直到不再需要一个数字或不再需要。

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;
}
于 2013-09-17T01:01:20.023 回答