convert char to int ascii in c function
To convert a char
to its corresponding ASCII value in C, you can use the int
typecast. Here is a step-by-step explanation:
Declare a
char
variable to store the character whose ASCII value you want to find. For example, let's say you have a variable namedmyChar
of typechar
.Declare an
int
variable to store the ASCII value. For example, let's say you have a variable namedasciiValue
of typeint
.Assign the
char
value to theint
variable using typecasting. Typecasting is done by enclosing the variable you want to convert inside parentheses and specifying the target type before it. In this case, you would useasciiValue = (int)myChar;
.The
asciiValue
variable now holds the ASCII value of the character stored inmyChar
.
Here is an example code snippet that demonstrates the conversion:
#include <stdio.h>
int main() {
char myChar = 'A';
int asciiValue;
asciiValue = (int)myChar;
printf("ASCII value of %c is %d\n", myChar, asciiValue);
return 0;
}
In this example, the character 'A'
is converted to its corresponding ASCII value and stored in the asciiValue
variable. The printf
statement then displays the character and its ASCII value on the console.
You can replace 'A'
with any character you want to convert, and the code will give you the corresponding ASCII value.