c语言下的gb2312和utf8及unicode之间的互相转换

仅仅针对汉字(每个汉字在UTF-8编码中占3个字节),如果字符串中有英文,就有麻烦了,因为英文在UTF-8编码中只有一个字节。另外有的字符会占用更多的字节。所以这个类并不适用。再参考一些文章,给出转换方式如下:


//gb2312 to unicode
int wLen = MultiByteToWideChar(CP_ACP, 0, lpszText, -1, NULL, 0);
LPWSTR wStr = new WCHAR[wLen];
MultiByteToWideChar(CP_ACP, 0, lpszText, -1, wStr, wLen);


//unicode to utf8
int aLen = WideCharToMultiByte(CP_UTF8, 0, wStr, -1, NULL, 0, NULL, NULL);
char* converted = new char[aLen];
WideCharToMultiByte(CP_UTF8, 0, wStr, -1, converted, aLen, NULL, NULL);


//utf8 to unicode
int wLen2 = MultiByteToWideChar(CP_UTF8, 0, converted, -1, NULL, 0);
LPWSTR wStr2 = new WCHAR[wLen2];
MultiByteToWideChar(CP_UTF8, 0, converted, -1, wStr2, wLen2);


//unicode to gb2312
int aLen2 = WideCharToMultiByte(CP_ACP, 0, wStr2, -1, NULL, 0, NULL, NULL);
char* converted2 = new char[aLen2];
WideCharToMultiByte(CP_ACP, 0, wStr, -1, converted2, aLen2, NULL, NULL);

 

代码里面还缺少内存的释放,这个就不补上了。

 

你可能感兴趣的:(C++,理论篇)