chevron_left
211 points
11 4 3

Convert a char to an int

We have two techniques for converting a single character to an integer type, as seen below:

1) Through Casting:

To convert a single character to its integer equivalent, we can utilize the casting operation. The ASCII equivalent of the character will be displayed in this scenario.

Consider the following conversion:

 char a = 'A';

 int num = (int) a;

 

In this example, the value of ‘num' will be 65, which is the ASCII equivalent of the character ‘A'.

If we wish to convert a number character to an integer value, we can perform the following operation.

 

 char a = '2';

 int num = a-48;

The ASCII value for 0 is 48 in this case. The second line, a-48, implicitly translates char a to its ASCII counterpart before subtracting it from 48 (50-48), yielding the integer value 2.

More Posts

Check if char is a number. Lalit Kumar - Jun 18, 2020
How to convert int to char c++? Lalit Kumar - Jul 5, 2020
How to convert int to string in C++? Lalit Kumar - Jul 13, 2020
How to convert char to string in C++? Lalit Kumar - May 12, 2020
How to convert string to char in C++? Lalit Kumar - May 10, 2020
How to Add a Char to a String in C++? Lalit Kumar - Sep 6, 2020
ISO C++ forbids converting a string constant to char* Lalit Kumar - Apr 16, 2020
How to convert int to char[] in java mhfaisal - Jun 2
Get a char from a string C++ hhh98hd - Aug 16
Invalid conversion from char to const char* C++ hhh98hd - Aug 2