Converting ascii hex values to hex bytes

Matthew Smith msmith%peruvian.utah.edu at cs.utah.edu
Thu Oct 18 05:32:23 AEST 1990


In article <298 at cti1.UUCP> mpledger at cti1.UUCP (Mark Pledger) writes:
>I have a little stumper of a question.  I am writing software that accesses
>a configuration file that stores IP addresses.  The IP addresses are stored
>as raw hex bytes.  For example, an IP address of say 122.10.10.44 is stored
>in the configuration file as 4 bytes 7A-0A-0A-2C.  Now I am using fread()
>and fwrite() to get a lot of different configuration data.  What I want to 
>do is to be able to convert 122.10.10.44 into a character string of 4 bytes
>that equals "\x7a\x0a\x0a\x2c".  How can I convert the ascii representation
>into hex?  I tried using itoa(), but the result is in ascii character format
>so if you used itoa(44,result,16), result[] = "2C".  When written to disk,
>the result[] string is actually written to disk as an ascii 2 (32h) and an
>ascii C (43h).  What I want is one byte equalling "\x2c".
>
>Can anybody give me a hand?  Thanks in advance.

Well, I'm not sure I understand you correctly, because if I do, then things
will be fairly simple.  In C, there is no difference in the way a char and an
integer are represented, except that a char only has 4 bits as opposed to 8.
As a matter of fact, chars are only integers that range from 0 to 255.  Maybe
the following piece of code will help clarify things:


char a;

a=64;
printf("%c, %x\n",a,a);

you'll get an output of "a" and "40" repectively.  "a" being the ascii 
value of 64, and "40" being the hex value of 64.

Using this idea, you should just read all of the numbers into char variables
and then print them out in hex.


>Sincerely,
>
>
>Mark Pledger
>


I hope this helps...

(I'm sure this is going to bring on a huge discussion on how having a "char"
variable is NOT the same thing as an integer between 0 and 255, and how K&R 
says this, and Joe says that, and the other thing.  So, please forgive me
for making such a statement and let's not bog down the net with such trivial
details)

Matt Smith



More information about the Comp.lang.c mailing list