Reputation: 2180
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).
Upvotes: 15
Views: 140526
Reputation: 1
Just typecast it to integer type that will automatically convert it to it's corresponding ASCII value.
#include <iostream>
using namespace std;
char c = 'a';
printf("%d",int(c));
Upvotes: 0
Reputation: 76488
#include <iostream>
char mychar = 'k';
int ASCIItranslate(char ch) {
return ch;
}
int main() {
std::cout << ASCIItranslate(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?
Upvotes: 0
Reputation: 1168
To 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);
Upvotes: 1
Reputation: 948
In C++, you could also use static_cast<int>(k)
to make the conversion explicit.
Upvotes: 5
Reputation: 133629
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.
Upvotes: 8
Reputation: 249592
Just do this:
int(k)
You're just converting the char to an int directly here, no need for a function call.
Upvotes: 24