利用纯c++和windows api实现gb2312和utf-8两种编码格式的转换

为什么同样的字符串在两台主机上,会出现一个显示正常,一个显示乱码的情况呢?

答案:编码方式不匹配。

解释:任何内容在计算机中的存储形式都是二进制,不论是在内存中还是在硬盘中。所以,同一个字符串在两台主机上的二进制存储是一模一样的。只是将这个二进制数据呈现时,发生了变化。呈现字符串的过程就是对字符串进行编码,并按照字符集找到该编码对应的符号,并显示出来的过程。所以出现了上面乱码的问题。所以,在utf8编码和gb2312编码下都显示正确、且相同的汉语文本,那么他们对应的二进制数据肯定不一样。这样表达可能更容易理解。

出现乱码怎么办?按下面的步骤办:

1,找到传过来的字符串的原始编码方式

2,找到你主机显示字符串的默认编码方式

3,转码

原文地址:点击打开

//UTF-8到GB2312的转换

std::string U2G(const char* utf8)
{
int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len+1];
memset(wstr, 0, len+1);
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[len+1];
memset(str, 0, len+1);
WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
if(wstr) delete[] wstr;
std::string strGb2312 = str;
if(str) delete[] str;
return strGb2312;
}

//GB2312到UTF-8的转换

std::string G2U(const char* gb2312)
{
int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len+1];
memset(wstr, 0, len+1);
MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[len+1];
memset(str, 0, len+1);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
if(wstr) delete[] wstr;
std::string strUtf8 = str;
if(str) delete[] str;
return strUtf8;
}

猜你喜欢

转载自blog.csdn.net/jigetage/article/details/83352720
今日推荐