Re: C18. How to convert text "A" to its ASCII code, 65.
After coming across this thread, I felt I needed to clarify a few facts concerning C types.
I want to get the ASCII code of a character string like "A" (not a numerical string like "5").
I the above case the result would be an 8-bit interger with a value of 65.
I do I do that?
I have searched invane without success. I cannot find a function that does that.
The reason you are unable to find a function or routine which converts a character into an integer value, is due to the fact no conversion is necessary.
All four of the following C statements produce EXACTLY the same result:
Code:
unsigned char c1 = 'A';
unsigned char c2 = 0b01000001;
unsigned char c3 = 0x41;
unsigned char c4 = 65;
After the above statements are executed:
There is NO difference between the values contained in all four variables, it is in fact the SAME value.
Alex touched on this point in
Post #9.
How the contents of four variables is interpreted is solely depended on your C code which accesses the value contained in any of the four variables.
I want an interger that cointain the number 65 which is the ASCII code for "A".
Simple.
The variable
c1 now contains the value 65, or 0x41 or 0b01000001 or 'A', depending on how it is interpreted.
For example:
Code:
unsigned int c1 = 'A';
unsigned int c2 = 'B';
unsigned int c3;
c3 = c1 + c2;
The variable
c3 now contains the value 131 or 0x83 or 0b010000011, once again depending on how you would like to interpret it.
You could achieve the same result by the following:
Code:
unsigned int c3;
c3 = 'A' + 'B';
The variable
c3 now contains the value 131 or 0x83 or 0b010000011, once again depending on how you would like to interpret it.
Solution found.
Code:
unsigned char i;
char mystr[1];
i='C'; // i is assigned the ASCII value 67
printf("ASCII: %d\n\r",i);
The output is 67 wich is the ASCII code of "C"
Actually the printf() routine has absolutely no effect on the contents of variable
i in your code above.
It simply interprets or formats the value by the
Conversion Specification you provided, in this case
%d.
The following is valid code and demonstrates my previous assertions:
Code:
unsigned char i;
i='C'; // i is assigned the ASCII value 67
printf("Signed Integer: %d, ASCII: %c, HEX: %X \n\r", i, i, i);
Typical Output:
Signed Integer: 67, ASCII: C, HEX: 43
Although exact results depend on compiler, the above output demonstrations how a single value can be formatted several ways depending only the
Conversion Specifications provided leaving the actual value unchanged.
You may also find the routine sprintf() helpful if you need to format the contents of variables in specific ways and then store the results in a string buffer.
BigDog