How do I convert a char to an int in C and C++?
In C and C++, there are two common scenarios when converting a character (char
) to an integer (int
):
- You want the ASCII (or Unicode) code of the character.
- You want the numerical value if the character represents a digit (e.g.,
'7'
→7
).
1. Getting the Character’s ASCII Code
Simply cast the char
to an int
:
char c = 'A'; int code = (int)c; // code now holds 65 if ASCII is used
- In many compilers and systems,
char
is signed by default, but for ASCII code extraction, it’s safer to do(unsigned char)c
if you’re dealing with extended characters above 127. - This form of casting yields the character’s numeric encoding (commonly ASCII on most modern systems).
2. Converting a Digit Character to Its Numeric Value
If the char
is a digit (e.g., '0'
..'9'
), subtract '0'
to get its integer equivalent:
char digitChar = '7'; int digitValue = digitChar - '0'; // digitValue = 7
- This works because in ASCII (and Unicode), the characters
'0'
..'9'
are in consecutive order. - Make sure you validate that the character is indeed a digit (e.g.,
'0' <= digitChar && digitChar <= '9'
) if there’s any uncertainty about input data.
3. Example
#include <stdio.h> int main(void) { char c1 = 'A'; int asciiCode = (int)c1; // 65 in ASCII printf("ASCII code of '%c' is %d\n", c1, asciiCode); char c2 = '9'; int numericValue = c2 - '0'; // 9 printf("Numeric value of '%c' is %d\n", c2, numericValue); return 0; }
Edge Cases & Tips
- Non-Digit Characters: If you do
c - '0'
on a non-digit character (e.g.,'A'
), the result won’t make sense as a valid number. It’s good practice to check ifc
is between'0'
and'9'
first. - Wide Characters (
wchar_t
): In C++ (and some C standards), wide characters follow a similar principle but might use different encoding sets. Casting rules still apply, but you should ensure consistent use of type (wchar_t
,char16_t
,char32_t
). - Locale or Non-ASCII Encodings: If your platform doesn’t use ASCII or you rely on locale-specific encodings, the numerical code might differ. For standard ASCII digit conversions,
'0'..'9'
remain consecutive in virtually all common encodings (including UTF-8).
Further Learning
If you want to strengthen your fundamentals in C, C++ concepts, and data structures, consider these two courses from DesignGurus.io:
-
Grokking Data Structures & Algorithms for Coding Interviews
Build a solid foundation in essential data structures (like arrays, linked lists, trees, graphs) and understand the memory-level details that matter in C/C++. -
Grokking the Coding Interview: Patterns for Coding Questions
Learn the recurring coding patterns tested in interviews—making you quicker at problem identification and efficient solution design.
By knowing exactly how to interpret or convert characters in your code—whether for ASCII codes or digit values—you’ll write more robust input handlers and clearer logic in your C/C++ programs.