Path: utzoo!news-server.csri.toronto.edu!rutgers!uwm.edu!cs.utexas.edu!bcm!shell!shell!rjohnson From: rjohnson@shell.com (Roy Johnson) Newsgroups: comp.lang.c Subject: Re: Converting between bases Message-ID: Date: 6 Mar 91 16:09:15 GMT References: <62375@eerie.acsu.Buffalo.EDU> Sender: usenet@shell.shell.com (USENET News System) Distribution: usa Organization: Shell Development Company, Bellaire Research Center, Houston, TX Lines: 47 In-Reply-To: cloos@acsu.buffalo.edu's message of 28 Feb 91 12:29:42 GMT In article <62375@eerie.acsu.Buffalo.EDU> cloos@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