"1234" ==> 1234 (char * ==> int)

Norbert Schlenker nfs at hart.Princeton.EDU
Sat Dec 15 12:34:37 AEST 1990


In article <1990Dec12.215359.5378 at cs.utk.edu> lape at .cs.utk.edu (Bryon S. Lape) writes:
>	I need to know how to convert a string of numbers into an int.
>For example, "1234" ==> 1234.  I am interested in all theories, so please
>send whatever you know or think.  Also, please e-mail the responses.

Here's a theory of conversion a couple of us thought up while playing
bridge the other night.  Take the outputs from your system standard
random number generator, convert them to a string, and compare them to
the input string.  If the strings don't match, try another random number.
If your random number generator is full period and the input string is
in range and in canonical form, this approach is guaranteed to succeed.

Following is some code to implement this incredible new theory.  We tested
the code successfully on a new 24 MIPS DEC machine that is just undergoing
shakedown testing here.  Conversion of "1234" to integer form took a mere
907 minutes of CPU time.

We are currently examining a few alternative theories.  Promising candidates
include hashing techniques, divide and conquer methods, and a still nebulous
proposal to map strings into flow networks which can then be solved by
your very own proprietary network flow code.  The more systems oriented
people here have suggested a combination of the above techniques, perhaps
with all running in parallel via forked processes and with communication
over pipes.

Adam Buchsbaum
Norbert Schlenker

-------------------------------------------------------------------------
/* An implementation of an alternative theory for converting C strings
 * to the corresponding integer.  Note that this routine requires the
 * supplied rand() function to exhaust the entire space of integers
 * at some point.  Beware of systems which cannot guarantee this.
 * Note also that the input string had better be in canonical form:
 * left justified, no leading zeros, no sign, no extraneous trash.
 *
 * Interface:
 *   int dweeb(char *string);
 */

#define MAXINT_LEN 10		/* maximum digits in an integer */

void srand();
int rand();

char *itoa(n)
int n;
{
  static char s[MAXINT_LEN + 1];
  char *p;

  p = &s[MAXINT_LEN];
  *p = '\0';
  while (n != 0) {
    *--p = '0' + n % 10;
    n /= 10;
  }
  return p;
}

int dweeb(p)
char *p;
{
  int candidate;		/* potential integer equivalent of parameter */
  char *candidate_string = "";	/* pointer to string equivalent of candidate */

  srand(1);
  while (strcmp(p, candidate_string) != 0) {
    candidate = rand();
    candidate_string = itoa(candidate);
  }
  return candidate;
}



More information about the Comp.lang.c mailing list