Advertisement
tranerius

utf8/win1251 converter

Feb 9th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. enum encode_mode {
  2.     UTFtoWIN,
  3.     WINtoUTF
  4. };
  5.  
  6. std::string encoder(std::string text_to_encode, int encode_mode) {
  7.     BSTR bstrWide;
  8.     int length;
  9.     char *text = new char[text_to_encode.size() + 1];
  10.     for (int i = 0; i < text_to_encode.size(); i++) {
  11.         text[i] = text_to_encode[i];
  12.     }
  13.     text[text_to_encode.size()] = '\0';
  14.     if (encode_mode == encode_mode::UTFtoWIN) {
  15.         length = MultiByteToWideChar(CP_UTF8, 0, text, strlen(text), NULL, NULL);
  16.         bstrWide = SysAllocStringLen(NULL, length);
  17.         MultiByteToWideChar(CP_UTF8, 0, text, strlen(text), bstrWide, length);
  18.         length = WideCharToMultiByte(1251, 0, bstrWide, -1, NULL, 0, NULL, NULL);
  19.         char *text_1251 = new char[length];
  20.         WideCharToMultiByte(1251, 0, bstrWide, -1, text_1251, length, NULL, NULL);
  21.         SysFreeString(bstrWide);
  22.         text_to_encode.clear();
  23.         for (int i = 0; i < strlen(text_1251); i++) {
  24.             text_to_encode += text_1251[i];
  25.         }
  26.         delete[]text_1251;
  27.     }
  28.     else if (encode_mode == encode_mode::WINtoUTF) {
  29.         length = MultiByteToWideChar(1251, 0, text, strlen(text), NULL, NULL);
  30.         bstrWide = SysAllocStringLen(NULL, length);
  31.         MultiByteToWideChar(1251, 0, text, strlen(text), bstrWide, length);
  32.         length = WideCharToMultiByte(CP_UTF8, 0, bstrWide, -1, NULL, 0, NULL, NULL);
  33.         char *text_u8 = new char[length];
  34.         WideCharToMultiByte(CP_UTF8, 0, bstrWide, -1, text_u8, length, NULL, NULL);
  35.         SysFreeString(bstrWide);
  36.         text_to_encode.clear();
  37.         for (int i = 0; i < strlen(text_u8); i++) {
  38.             text_to_encode += text_u8[i];
  39.         }
  40.         delete[]text_u8;
  41.     }
  42.     delete[]text;
  43.     return text_to_encode;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement