Summary: Converting ascii hex to pure hex values

Michael J. Eager eager at ringworld.Eng.Sun.COM
Wed Oct 31 15:46:54 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.  I know I
>can use scanf() or cast a char to int (for a single char).  I DID'NT want to
>use scanf() and casting does not work for my question.  The original question
>went something like this:  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
>currently use atoi() and just write out the int to disk.  I am interested in
>creating (or finding) a routine that will take a character string as the 
>argument, and returning the hex result in the same character string.


Well, I have to agree that the previous posting wasn't clear; but
I'm not sure this one makes anything more clear.

If you want to convert the ascii representation of a 8 bit hex value
into that value, here is a simple way: (Although returning the value
in the same string seems abhorrent.

void atox (char *s)
{
  char * p = s;
  int left, right;

  while (*s) {
    left = *s - '0';
    right = *(s+1) - '0';	/* Better hope they come in pairs */
    if (left > 9) left = toupper(left + '0') - 'A' + 10;
    if (right > 9) right = toupper(right + '0') - 'A' + 10;
    *p = (left << 4) + right;
    p++;
    s += 2;
    }
}


Note that you need to know how many characters you are passing to
this function so you will know how many bytes are returned.

-- Mike Eager



More information about the Comp.lang.c mailing list