std::string to std::wstring (C++)


SUBMITTED BY: Guest

DATE: April 23, 2013, 5 p.m.

FORMAT: C++

SIZE: 2.0 kB

HITS: 1544

  1. //
  2. // Okzoniom::RPG
  3. // Copyright (C) 2010 - 2013
  4. // Okzoniom::RPG Development Team
  5. // - Louis SCHNELLBACH
  6. //
  7. // This file is part of the Okzoniom::RPG Game.
  8. //
  9. #include <iostream>
  10. #include <cstring>
  11. #include <sstream>
  12. #include "Utils.h"
  13. #include "Log.h"
  14. #include "Lua.h"
  15. std::wstring okz::wide(const std::string& s)
  16. {
  17. std::wstring wideString;
  18. uint32_t ascii = 0;
  19. uint32_t nAscii = 0;
  20. uint8_t byte[4] = {0,0,0,0};
  21. uint8_t ctrl[3] = {0xF0, 0xE0, 0xC0};
  22. uint8_t mask[3] = {0x7, 0xF, 0x1F};
  23. uint8_t nbByte = 0;
  24. for(uint32_t i = 0; i < s.size(); ++i)
  25. {
  26. //Get each byte for the code
  27. ascii = s[i];
  28. // BYTE 0 --> 3
  29. for(int j = 0; j < 4; ++j)
  30. byte[j] = ascii >> ((3-j)*8);
  31. //We have still some byte to treat
  32. if(nbByte > 0)
  33. {
  34. --nbByte;
  35. nAscii = (nAscii << 6) | (byte[3-nbByte] & 0x3F);
  36. //Add new char !
  37. if(nbByte == 0)
  38. wideString.push_back(nAscii);
  39. }
  40. else
  41. {
  42. //Ok, new char
  43. //Simple test to know if multi byte:
  44. if((char)ascii > 0)
  45. {
  46. //1-Byte ASCII, so treated here, and then next char !
  47. wideString.push_back(ascii);
  48. }
  49. else
  50. {
  51. //So only need to check the first 3 bytes
  52. for(int j = 0; j < 3; ++j)
  53. if(nbByte > 0)
  54. break;
  55. else nbByte = byte[2-j] & ctrl[2-j];
  56. //Get the correct byte number
  57. nbByte = (nbByte == 0xF0 ? 3 : nbByte == 0xE0 ? 2 : 1);
  58. nAscii = 0 | ascii & mask[3-nbByte];
  59. }
  60. }
  61. }
  62. return wideString;
  63. }

comments powered by Disqus