Convert a char to ASCII in C++
This post will discuss how to convert a char to ASCII code in C++.
A simple solution to convert a char to ASCII code in C++ is using type-casting. Here’s an example of its usage:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> int main() { char c = 'K'; int i = int(c); std::cout << i << std::endl; // 75 return 0; } |
Alternatively, we can implicitly convert a char to ASCII code by assigning the char to an int. This works since a char is already a number.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> int main() { char c = 'K'; int i = c; std::cout << i << std::endl; // 75 return 0; } |
C++ also offers four types of casting operators – static_cast, dynamic_cast, reinterpret_cast, and const_cast. To make the conversion safe and explicit, consider using static_cast.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> int main() { char c = 'K'; int i = static_cast<int>(c); std::cout << i << std::endl; // 75 return 0; } |
That’s all about converting a char to ASCII code in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)