String to ASCII value and vice-versa.
-
This is for C++.
I have a String variable containing alphanumerical characters.
How can I get the ASCII value of each character?
For example, if my String variable is "a1b2", how can I get the ASCII values of each character (97,49,98,50)?And, if I have an Int32 variable containing a numerical value, how can I create a String out of that ASCII value.
For example, if my Int32 variable has a value of 102, how can I create a String that contains "f" ?I have been going through the documentation but these simple conversions, that are so basic in other languages, are not simple to understand in the C++ documentation.
-
Maybe not the best solution but this seems to work:
maxon::String str = "a1b2"_s; Int32 ascii = 102; // convert string to ASCII for (Int32 i = 0; i < str.GetLength(); ++i) { char c = (char)str[i]; Int32 a = (Int32)str[i]; ApplicationOutput("'@' position @ has char @ (ascii = @)", str, i, c, a); } // ASCII to string { maxon::String ascii2str; ascii2str.AppendChar(ascii); ApplicationOutput("ascii value @ results into string '@'", ascii, ascii2str); } // alternative { maxon::String ascii2str; iferr(ascii2str.Insert(0, char(ascii))) {} ApplicationOutput("(alternative) ascii value @ results into string '@'", ascii, ascii2str); }
Output to console:
'a1b2' position 0 has char 97 (ascii = 97) 'a1b2' position 1 has char 49 (ascii = 49) 'a1b2' position 2 has char 98 (ascii = 98) 'a1b2' position 3 has char 50 (ascii = 50) ascii value 102 results into string 'f' (alternative) ascii value 102 results into string 'f'
-
Thank you very much.
It seems to work -
Hello,
just FYI: you find information on how to access individual characters from a string in the manual: String Manual
Also, one of our examples includes checking the ASCII value of a given character: streamconversion_impl.cpp
If your question has been answered, please mark your thread as a question and set it to "solved".
best wishes,
Sebastian