6

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)

user2187476
  • 109
  • 1
  • 1
  • 6

3 Answers3

14

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'
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
8

Uhm, what's wrong with this:

#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;
}
Nik Bougalis
  • 10,495
  • 1
  • 21
  • 37
  • int x = c; is casting. What you are doing here is implicit casting, because 'x' is integer and 'c' is char. It is equivalent to int x = (int) c, (which is an explicit cast) – thinkquester Mar 19 '13 at 16:52
  • 8
    @thinkquester **no**, that's **NOT** casting. There's a difference between *casting* and *converting*. A cast is something explicit that a programmer does. There are no "implicit casts". – Nik Bougalis Mar 19 '13 at 16:53
  • 1
    Formally, this displays the value of `'A'` in whatever encoding the implementation uses. That's usually ASCII these days, but it's not required to be. – Pete Becker Mar 19 '13 at 17:27
  • @PeteBecker: Thanks for pointing that out, it was a "hidden assumption" I should have made clear. – Nik Bougalis Mar 19 '13 at 17:30
  • @NikBougalis - it's a hidden assumption that most programmers make. – Pete Becker Mar 19 '13 at 17:32
-1

You can use chars as is as single byte integers.

tom
  • 18,953
  • 4
  • 35
  • 35