Convert a char to ASCII?

I have tried many solutions to convert char to Ascii. And everyone has a problem.

One solution:

char A; int ValeurASCII = static_cast<int>(A); 

But VS mentions that static_cast is an invalid type conversion !!!

PS: my A is always one of the special characters (not numbers)

+4
source share
3 answers

A char is an integral type. When you write

 char ch = 'A'; 

you set the value of ch to any number that your compiler uses to represent the character 'A' . This is usually the ASCII code for 'A' these days, but it is not required. You almost certainly use a system using ASCII.

Like any number type, you can initialize it with a regular number:

 char ch = 13; 

If you want to do arithmetic by char value, just do this: ch = ch + 1; etc.

However, in order to display the value that you have to bypass the assumption in the iostreams library, you want to display char values ​​as characters, not numbers. There are several ways to do this.

 std::cout << +ch << '\n'; std::cout << int(ch) << '\n' 
+12
source

Hmm, what's wrong with that:

 #include <iostream> using namespace std; int main(int, char **) { char c = 'A'; int x = c; // Look ma! No cast! cout << "The character '" << c << "' has an ASCII code of " << x << endl; return 0; } 
+5
source

You can use characters as unit byte integers.

0
source

All Articles