ASCII TO STRING Conversion

Feb 9, 2016 at 11:04pm
Hi, I have been searching a while for a way to convert acsii code to and from a string, any help is appreciated.
Feb 9, 2016 at 11:55pm
No conversion necessary.

1
2
int val = 'a'; //val will print 97
char ch = 97; //ch will print 'a' 
Feb 9, 2016 at 11:57pm
By 'ASCII code', do you mean, say, you have a string of numbers 65 101 116 and you want to convert it to a string "Eat"?

Well, converting an int to a char should work. chars store the letters by (usually) their ASCII representations anyway, so the following should work:
1
2
3
int x = 97;
char c = static_cast<char>(x);
std::cout << c << '\n'; // a 

I'll leave it to you to work out how to convert a string of numbers into a string of characters :)
Last edited on Feb 9, 2016 at 11:57pm
Feb 10, 2016 at 1:03am
48 65 6c 6c 6f is hex for Hello, I wanna translate this to char.
Feb 10, 2016 at 1:27am
You can use std::hex to signify you are reading hexadecimal values:
1
2
3
int x;
std::cin >> std::hex >> x;
std::cout << static_cast<char>(x) << '\n';

Alternatively, if you already have a string with it in, you can use std::stringstream and std::hex like above or use std::stoi:
1
2
3
std::string s = "48";
int x = std::stoi(s, nullptr, 16);
std::cout << static_cast<char>(x) << '\n';
Last edited on Feb 10, 2016 at 1:27am
Feb 10, 2016 at 1:35am
What if its a very long string, like for example 49 20 4c 49 4b 45 20 59 4f 55 52 20 53 4f 43 4b 20 4d 38
Topic archived. No new replies allowed.