I would like to convert a char to its ASCII int value.
I could fill an array with all possible values and compare to that, but it doesn't seems right to me. I would like something like
char mychar = "k" public int ASCItranslate(char c) return c ASCItranslate(k) // >> Should return 107 as that is the ASCII value of 'k'. The point is atoi() won't work here as it is for readable numbers only.
It won't do anything with spaces (ASCII 32).
26 Answers
Just do this:
int(k) You're just converting the char to an int directly here, no need for a function call.
A char is already a number. It doesn't require any conversion since the ASCII is just a mapping from numbers to character representation.
You could use it directly as a number if you wish, or cast it.
In C++, you could also use static_cast<int>(k) to make the conversion explicit.
Do this:-
char mychar = 'k'; //and then int k = (int)mychar; 3To Convert from an ASCII character to it's ASCII value:
char c='A'; cout<<int(c); To Convert from an ASCII Value to it's ASCII Character:
int a=67; cout<<char(a); #include <iostream> char mychar = 'k'; int ASCIItranslate(char ch) { return ch; } int main() { std::cout << ASCIItranslage(mychar); return 0; } That's your original code with the various syntax errors fixed. Assuming you're using a compiler that uses ASCII (which is pretty much every one these days), it works. Why do you think it's wrong?