Conversion of char to int C program – Convert a character digit to the corresponding integer in C program. For example, if the character is ‘5’ (char c =’5’) then corresponding int number will be 5.
The conversion is very simple and just we have to Subtract ‘0’ like below example.
int i = c – ‘0’;
How subtracting ‘0′ help find char to int digit?
Subtracting the decimal ASCII value of 0 (zero) from decimal ASCII value of entered digit into char format results to corresponding digit. For example, consider the char digit ‘5’, its decimal ASCII value is 53 and 0 has decimal ASCII value 48. On subtraction it gives int value 5. (‘5’ -‘0’ => 53 – 48 = 5).
Char to int C Program example
#include<stdio.h>
/*------ Char to int digit conversion --------*/
//parameter : pass char
//return : int (converted corresponding digit)
int charToInt(char c){
int num = 0;
//Substract '0' from entered char to get
//corresponding digit
num = c - '0';
return num;
}
/* You can write one liner statement e.g.
int charToInt(char c){
return c - '0';
}
*/
int main(){
char c;
int numer=0;
printf("Enter digit Character :");
scanf("%c",&c);
numer = charToInt(c);
printf("Character %c -> number %d",c,numer);
return 0;
}
Output:
Enter digit Character :5
Character 5 -> number 5