资源描述:
《多字节与utf-8、unicode之间的转换》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、多字节与UTF-8、Unicode之间的转换1.2.3.// 多字节编码转为UTF8编码 4.bool MBToUTF8(vector& pu8, const char* pmb, int32 mLen) 5.{ 6. // convert an MBCS string to widechar 7. int32 nLen = MultiByteToWideChar(CP_ACP, 0, pmb, mLen, NULL, 0); 8. 9. WCHAR* lpszW = NU
2、LL; 10. try 11. { 12. lpszW = new WCHAR[nLen]; 13. } 14. catch(bad_alloc &memExp) 15. { 16. return false; 17. } 18. 19. int32 nRtn = MultiByteToWideChar(CP_ACP, 0, pmb, mLen, lpszW, nLen); 20. 21. if(nRtn != nLen) 22. { 23. delet
3、e[] lpszW; 24. return false; 25. } 26. // convert an widechar string to utf8 27. int32 utf8Len = WideCharToMultiByte(CP_UTF8, 0, lpszW, nLen, NULL, 0, NULL, NULL); 28. if (utf8Len <= 0) 29. { 30. return false; 31. } 32. pu8.resize(utf8Le
4、n); 33. nRtn = WideCharToMultiByte(CP_UTF8, 0, lpszW, nLen, &*pu8.begin(), utf8Len, NULL, NULL); 34. delete[] lpszW; 35. 36. if (nRtn != utf8Len) 37. { 38. pu8.clear(); 39. return false; 1. } 2. return true; 3.} 4. 5.// UTF8编码转为多字节编码
5、 6.bool UTF8ToMB(vector& pmb, const char* pu8, int32 utf8Len) 7.{ 8. // convert an UTF8 string to widechar 9. int32 nLen = MultiByteToWideChar(CP_UTF8, 0, pu8, utf8Len, NULL, 0); 10. 11. WCHAR* lpszW = NULL; 12. try 13. {
6、14. lpszW = new WCHAR[nLen]; 15. } 16. catch(bad_alloc &memExp) 17. { 18. return false; 19. } 20. 21. int32 nRtn = MultiByteToWideChar(CP_UTF8, 0, pu8, utf8Len, lpszW, nLen); 22. 23. if(nRtn != nLen) 24. { 2
7、5. delete[] lpszW; 26. return false; 27. } 28. 29. // convert an widechar string to Multibyte 30. int32 MBLen = WideCharToMultiByte(CP_ACP, 0, lpszW, nLen, NULL, 0, NULL, NULL); 31. if (MBLen <=0) 32. { 33. r
8、eturn false; 34. } 35. pmb.resize(MBLen); 36. nRtn = WideCharToMultiByte(CP_ACP, 0, lpszW, nLen, &*pmb.begin(), MBLen, NULL, NULL); 37. delete[] lpszW; 38. 39. if(nRtn != MBLen) 40. { 41. pmb.clea