Summary: Converting ascii hex to pure hex values

Richard A. O'Keefe ok at goanna.cs.rmit.oz.au
Mon Oct 29 12:39:45 AEST 1990


In article <302 at cti1.UUCP>, mpledger at 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.



More information about the Comp.lang.c mailing list