Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a char to ASCII? [closed]

I have tried lots of solutions to convert a char to Ascii. And all of them have got a problem.

One solution was:

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 chars (and not numbers)

like image 876
user2187476 Avatar asked Mar 19 '13 16:03

user2187476


1 Answers

A char is an integral type. When you write

char ch = 'A';

you're setting the value of ch to whatever number your compiler uses to represent the character 'A'. That's usually the ASCII code for 'A' these days, but that's not required. You're almost certainly using a system that uses ASCII.

Like any numeric type, you can initialize it with an ordinary number:

char ch = 13;

If you want do do arithmetic on a char value, just do it: ch = ch + 1; etc.

However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char values as characters rather than numbers. There are a couple of ways to do that.

std::cout << +ch << '\n';
std::cout << int(ch) << '\n'
like image 50
Pete Becker Avatar answered Nov 15 '22 22:11

Pete Becker