C++转换unicode utf-8 gb2312编码

时间:2023-03-09 01:26:05
C++转换unicode utf-8 gb2312编码

windows开发环境下用VC++6.0 对unicode 、utf-8、 gb2312 三种编码格式之间的转换方法:

  1. #include <iostream>
  2. #include <string>
  3. #include <Windows.h>
  4. using namespace std;
  5. void unicodeToUTF8(const wstring &src, string& result)
  6. {
  7. int n = WideCharToMultiByte( CP_UTF8, 0, src.c_str(), -1, 0, 0, 0, 0 );
  8. result.resize(n);
  9. ::WideCharToMultiByte( CP_UTF8, 0, src.c_str(), -1, (char*)result.c_str(), result.length(), 0, 0 );
  10. }
  11. void unicodeToGB2312(const wstring& wstr , string& result)
  12. {
  13. int n = WideCharToMultiByte( CP_ACP, 0, wstr.c_str(), -1, 0, 0, 0, 0 );
  14. result.resize(n);
  15. ::WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, (char*)result.c_str(), n, 0, 0 );
  16. }
  17. void utf8ToUnicode(const string& src, wstring& result)
  18. {
  19. int n = MultiByteToWideChar( CP_UTF8, 0, src.c_str(), -1, NULL, 0 );
  20. result.resize(n);
  21. ::MultiByteToWideChar( CP_UTF8, 0, src.c_str(), -1, (LPWSTR)result.c_str(), result.length());
  22. }
  23. void gb2312ToUnicode(const string& src, wstring& result)
  24. {
  25. int n = MultiByteToWideChar( CP_ACP, 0, src.c_str(), -1, NULL, 0 );
  26. result.resize(n);
  27. ::MultiByteToWideChar( CP_ACP, 0, src.c_str(), -1, (LPWSTR)result.c_str(), result.length());
  28. }
  29. void printByte(string str)
  30. {
  31. int i=0;
  32. for (i=0; i<str.length(); i++)
  33. {
  34. printf("%X ",(unsigned char)str.at(i));
  35. }
  36. printf("\n");
  37. }
  38. void wprintByte(wstring str)
  39. {
  40. int i=0;
  41. for (i=0; i<str.length()*sizeof(wchar_t); i++)
  42. {
  43. printf("%X ",*((unsigned char*)str.c_str()+i));
  44. }
  45. printf("\n");
  46. }
  47. int main()
  48. {
  49. string strText = "AB汉字";
  50. string strUTF8;
  51. wstring wstrUnicode;
  52. string strGB2312;
  53. gb2312ToUnicode(strText, wstrUnicode);
  54. printf("Unicode=");
  55. wprintByte(wstrUnicode);
  56. unicodeToUTF8(wstrUnicode, strUTF8);
  57. printf("UTF-8  =");
  58. printByte(strUTF8);
  59. utf8ToUnicode(strUTF8,wstrUnicode);
  60. printf("Unicode=");
  61. wprintByte(wstrUnicode);
  62. unicodeToGB2312(wstrUnicode,strGB2312);
  63. printf("GB2312 =");
  64. printByte(strGB2312);
  65. return 0;
  66. }

这里用“AB汉字”这样一个字符串做测试,它的ASCII编码为41 42 BA BA D7 D6
输出结果:

C++转换unicode utf-8 gb2312编码