Path: utzoo!attcan!uunet!munnari.oz.au!goanna!ok From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) Newsgroups: comp.lang.c Subject: Re: Summary: Converting ascii hex to pure hex values Message-ID: <4108@goanna.cs.rmit.oz.au> Date: 29 Oct 90 01:39:45 GMT References: <302@cti1.UUCP> Distribution: comp Organization: Comp Sci, RMIT, Melbourne, Australia Lines: 48 In article <302@cti1.UUCP>, mpledger@cti1.UUCP (Mark Pledger) writes: > I guess I did'nt make myself clear enough on my question though. ... > If you have a character string with the ascii > representation of hex values (e.g. s[] = "63", > which will be stored as TWO hex byte values \x9 & \x9. > I only want to store them as ONE hex byte of \x63. > Without using scanf() (or even sprintf()) what is the best (fasted for me) > way to convert a two-digit ascii code to a one digit hex code, > so I can put it back into the charater string s[], append a null, > and write it back out to disk. I still don't see what's wrong with using sscanf(). Suppose s currently points to "63\0" and you want it to point to "\x63\0". { unsigned i; sscanf(s, "%2x", &i); s[0] = i, s[1] = '\0'; } does the job just fine. If you want speed, use a table: char hexval[256]; /* for EBCDIC, ISO 646, or ISO 8859 */ void init_hexval() { unsigned char *p; for (p = (unsigned char *)"0123456789"; *p; p++) hexval[*p] = *p-'0'; for (p = (unsigned char *)"ABCDEF"; *p; p++) hexval[*p] = (*p-'A')+10; for (p = (unsigned char *)"abcdef"; *p; p++) hexval[*p] = (*p-'a')+10; /* this leaves hexval[c] UNDEFINED for characters */ /* c which are not in [0-9A-Fa-f] */ } Now do s[0] = (hexval[s[0]] << 16) + hexval[s[1]], s[1] = '\0'; and presto chango, the job is done. That is, of course, for the ultimate in speed with absolutely no error checking at all. If your objection to using C library functions applies only to sscanf(), what's wrong with strtol()? What I'm rather worried by is the "append a NUl and write it back out to disc" bit. Why append a NUL? Why not just do { int byte_value = (hexval[s[0]] << 16) + hexval[s[1]]; putchar(byte_value); } -- Fear most of all to be in error. -- Kierkegaard, quoting Socrates.