Advertisement
Combreal

utf8-16_conv.cpp

Apr 30th, 2021 (edited)
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. static std::string utf16ToUTF8(const std::wstring &s)
  2. {
  3.     const int size = ::WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, NULL, 0, 0, NULL);
  4.  
  5.     std::vector<char> buf(size);
  6.     ::WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, &buf[0], size, 0, NULL);
  7.  
  8.     return std::string(&buf[0]);
  9. }
  10.  
  11. CStringW UTF8toUTF16(const CStringA& utf8)
  12. {
  13.     CStringW utf16;
  14.     int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
  15.     if (len > 1)
  16.     {
  17.         wchar_t *ptr = utf16.GetBuffer(len - 1);
  18.         if (ptr) MultiByteToWideChar(CP_UTF8, 0, utf8, -1, ptr, len);
  19.         utf16.ReleaseBuffer();
  20.     }
  21.     return utf16;
  22. }
  23.  
  24. LPWSTR stringToLPWSTR(const std::string& instr)
  25. {
  26.     int bufferlen = ::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), NULL, 0);
  27.     LPWSTR widestr = new WCHAR[bufferlen + 1];
  28.     ::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), widestr, bufferlen);
  29.     widestr[bufferlen] = 0;
  30.     return widestr;
  31. }
  32.  
  33. std::string ws2s(const std::wstring& wstr)
  34. {
  35.     int size_needed = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), int(wstr.length() + 1), 0, 0, 0, 0);
  36.     std::string strTo(size_needed, 0);
  37.     WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), int(wstr.length() + 1), &strTo[0], size_needed, 0, 0);
  38.     return strTo;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement