I am trying to send text packets over the network using winsock. However the text is stored as wchar_t and I need to be able to convert the text into byte (char) format for sending over the network, which will then be converted back to wchar_t.
I've experimented with using ostringstream and have converted the wchar_t string of mine to what looks like byte format, however when I try to go the reverse I get a load of gibberish.
I can't seem to find any answers whilst looking online, so any help would be much appreciated.
OK here is some code that I played with.
std::wstring text( ieS("Hello") );
std::ostringstream ostr;
ostr.imbue( std::locale( ) );
ostr << text.c_str();
std::string text2 = ostr.str();
Convert to std::string to get char format.
std::wostringstream wostr;
wostr.imbue( std::locale( ) );
wostr << text2.c_str();
text = oss.str(); // gibberish
Convert back to std::wstring to get wchar_t format...
htons
orhtonl
- you shouldn't hardcode assumptions about the other side. There are two endian variants of UTF-16, so you should make an explicit choice there, but UTF-8 is endian-neutral and simply avoids the need for such a choice. – MSalters