Converting ascii hex values to hex bytes

Matthew Smith msmith%peruvian.utah.edu at cs.utah.edu
Fri Oct 19 06:49:05 AEST 1990


In article <31530022 at hpcvia.CV.HP.COM> brianh at hpcvia.CV.HP.COM (brian_helterline) writes:
>Matthew Smith writes:
>[(Mark Pledger) stuff deleted]
>
>>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.
>                                        ^^^^^^^^^^^^^^^^^^^^
>	WHAT?????? a char has 8 bits!!  4 bits yield values from 0-15.

Yeah yeah yeah.... I know...  I thought about it after I had sent it, and I 
figured I was gonna get flamed for it.  Bad day.

>>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);
>
>>Using this idea, you should just read all of the numbers into char variables
>>and then print them out in hex.
>
>	This is *exactly* what the original poster did NOT want!  He did
>	not want the hex value converted to 2 chars and output as a string,
>	he wanted to output 1 char whose ascii value was the hex value
>	he wanted.  (In this discussion, hex really isn't important, since
>	it it just the integer value and it can be thought of in hex, octal
>	binary, etc )
>

It doesn't put the output as a string.  You misunderstood what I was trying 
to get across.  A byte is stored as a series of 8 (yes, I AM awake today) bits
so whether or not you express them as a hex number of a decimal number makes
no difference to the machine.  If he reads in a number into a char, and then
does a printf %x, he'll get the decimal number in hex format, if he prints it
with a %c, he'll get the character with that ascii value.  So, all he has to
do is read in the numbers into chars.  If he is reading in the numbers as a 
string, ie: '1','2','2', all he has to do is do a atoi, which will return 
122 in a 16 bit integer, and then cast it into a char, and he'll have 122 in 
1 char.  ie:  The 1 character ascii value of a number.  

>
>>(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)
>	
>	Calling a char 4 bits is not trival.

I agree.  It was downright sloppy.

Matt Smith



More information about the Comp.lang.c mailing list