Converting between bases

Roy Johnson rjohnson at shell.com
Thu Mar 7 02:09:15 AEST 1991


In article <62375 at eerie.acsu.Buffalo.EDU> cloos at acsu.buffalo.edu (James H. Cloos) writes:
>Hello.

>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]+

>If someone could give me a jab into the right direction (either what to do
>or where to look) I'd be most grateful.  

The following will work if the strings are not so arbitrarily long that
the machine cannot numerically represent them:

char hexstr[9];		/* The final result string */
char numstring[33];	/* The input string */
unsigned i;		/* Just a loop variable */
long num;		/* Numerical value of numstring */

Binary:
for(i=num=0; numstring[i] != '\0'; ++i) {
  num *= 2;
  if (numstring[i] == '1') ++num;
}
sprintf(hexstr, "%x", num);

Octal:
sscanf(numstring, "%o", &num);
sprintf(hexstr, "%x", num);

Decimal:
sscanf(numstring, "%d", &num);
sprintf(hexstr, "%x", num);

This looks suspiciously like homework, so I've purposely used
library routines, which most professors don't want you to use,
but which are fine more most real work.

--
======= !{sun,psuvax1,bcm,rice,decwrl,cs.utexas.edu}!shell!rjohnson =======
Feel free to correct me, but don't preface your correction with "BZZT!"
Roy Johnson, Shell Development Company



More information about the Comp.lang.c mailing list