Converting between bases

Paul Falstad pfalstad at phoenix.Princeton.EDU
Fri Mar 1 17:00:22 AEST 1991


cloos at acsu.buffalo.edu (James H. Cloos) wrote:
>I need to be able to convert arbitrarily long strings which a guaenteed to
>match one of the regexps below (each one gets a different function) and
>output the hex equivilent (again in a string) optionally cut down to a
>specified number of hex digits.  (The least significant ones.)  The latter
>part I can take care of, but the former is giving me trouble.
>
>[01]+
>[0-7]+
>[0-9]+

strtol(3).

long binarytoi(char *s)
{
   return strtol(s,NULL,2);
}

long octaltoi(char *s)
{
   return strtol(s,NULL,8);
}

..

If you don't have strtol(3), here's a crippled version that will work
here: (hex conversions, as well as the base == 0 case, are left as an
exercise for the reader)

long strtol(char *s,char **x,int base)
{
long z;

   while (*s >= '0' && *s < '0'+base)
      z = z*base+(*s++-'0');
   if (x)
      *x = s;
   return z;
}

You can print hex with printf("%x\n",foo).

--
Paul Falstad, pfalstad at phoenix.princeton.edu PLink:HYPNOS GEnie:P.FALSTAD
How DO you delete a file called "-"?  For viewers at home, the answer is
coming up on your screen.  For those of you who wish to play it the hard
way, stand upside down with your head in a bucket of piranha fish.



More information about the Comp.lang.c mailing list