I need to implement this Java code in (unmanaged) c++:
byte[] b = string.getBytes("UTF8");
I’m new to c++, and can’t find anything to do this. It has to be platform independent, if possible. Using c++11 compiler.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Java
Stringis roughly equivalent tostd::u16string, a specialization ofstd::basic_string. I suggest you try something like…Note this relies on C++11; it might be sometime before your compiler vendor fully supports these features.
Here, we utilize the newly introduced
std::wstring_convertto convert from a wide-character UTF-16 string to the UTF-8 multibyte string viato_bytes(it also supports conversion in the other direction, too).This is made possible via the (also newly introduced)
std::codecvt_utf8_utf16conversion facet. It takes care of the actual conversion for us nicely.Besides that, it makes use of the new character literal prefixes added with C++11 — in particular,
u, which is forchar16_tUTF-16 strings 🙂 There are alsou8andUfor UTF-8 and UTF-32, respectively.PS
datais (as of C++11) guaranteed to be equal toc_strand therefore can be relied upon to be NUL-terminated.