Reputation: 112
I'm trying to convert a string of ASCII numbers to their corresponding string values.
For instance how can I convert a string such as 'This is good'
to a string of ASCII numbers or convert a string 84114117116104326510811997121115328710511011532
to the corresponding sentence?
Upvotes: 0
Views: 1213
Reputation: 1
try this
string encode="84114117116104326510811997121115328710511011532";
string str = encode;
int l=0;
l=str.length();
string decode1="";
//l--;
int i=0
char c;
while(i<=l){
c=str[i];
if( c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9'){
i++;
char c1=str[i];
string y;
y.push_back(c);
y.push_back(c1);
int num=stoi(y);
char c3=num;
decode1.push_back(c3);
i++;
}
if(c=='1'){
i++;
char c1=str[i];
i++;
char c2=str[i];
string y;
y.push_back(c);
y.push_back(c1);
y.push_back(c2);
int num=stoi(y);
char c3=num;
decode1.push_back(c3);
i--;
}
cout<<decode1;
}
Upvotes: 0
Reputation: 59988
From String to int it is easy you can use :
String str = "This is good";
String number = "";
for (char c : str.toCharArray()) {
number += (int) c;
}
But from int
to String
this is not possible, because you don't have any logic how you get cut your string to get the correspondence values, for example :
84114
this can be -> can be Th T(84) and h(114) orTVT
T(84) + VT(11) and 4( ) empty.
Upvotes: 1
Reputation: 11171
84114117116104326510811997121115328710511011532 can't be converted back, because : How should it be read ? 8 and 41 or 84 and 1 ? You need separators. And you will have to use charAt() :
String s="This is good";
String ascii="";
String separator=":";
for (int i=0; i < s.length; i++) {
int c=s.charAt(i);
ascii+=Integer.toString(c);
if (i < s.length-1) {
ascii+=separator;
}
}
//Converting it back :
String[] characters=ascii.split(separator);
String converted_back="";
for (String string:characters) {
converted_back+=new String(new char[]{(char)Integer.parseInt(string)});
}
Feel free to ask any question. Hope it helps you.
Upvotes: 1