windows下字符编码的转化函数

Posted jameflight

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了windows下字符编码的转化函数相关的知识,希望对你有一定的参考价值。

//GB2312到UTF-8的转换
static int GB2312ToUtf8(const char* gb2312, char* utf8)
{
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);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, utf8, len, NULL, NULL);
if(wstr) delete[] wstr;
return len;
}


//UTF-8到GB2312的转换
static int Utf8ToGB2312(const char* utf8, char* gb2312)
{
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);
WideCharToMultiByte(CP_ACP, 0, wstr, -1, gb2312, len, NULL, NULL);
if(wstr) delete[] wstr;
return len;
}

//GB2312到Unicode的转换
static int GB2312ToUnicode(const char* gb2312, char* unicode)
{
UINT nCodePage = 936; //GB2312
int len = MultiByteToWideChar(nCodePage, 0, gb2312, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len+1];
memset(wstr, 0, len+1);
MultiByteToWideChar(nCodePage, 0, gb2312, -1, wstr, len);
len = len*sizeof(wchar_t);
memcpy(unicode, wstr, len);
if(wstr) delete[] wstr;
return len;
}


//Unicode到GB2312的转换
static int UnicodeToGB2312(const char* unicode, int size, char*gb2312)
{
UINT nCodePage = 936; //GB2312
wchar_t* wstr = new wchar_t[size/2+1];
memcpy(wstr, unicode, size);
int len = WideCharToMultiByte(nCodePage, 0, wstr, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(nCodePage, 0, wstr, -1, gb2312, len, NULL, NULL);
if(wstr) delete[] wstr;
return len;
}

//UTF-8到Unicode的转换
static int Utf8ToUnicode(const char* utf8, char*unicode)
{
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);
memcpy(unicode, wstr, len);
if(wstr) delete[] wstr;
return len;
}


//Unicode到UTF-8的转换
static int UnicodeToUtf8(const char* unicode, int size, char* utf8)
{
wchar_t* wstr = new wchar_t[size/2+1];
memcpy(wstr, unicode, size);
int len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, utf8, len, NULL, NULL);
if(wstr) delete[] wstr;
return len;
}

以上是关于windows下字符编码的转化函数的主要内容,如果未能解决你的问题,请参考以下文章

python第三天:字符编码文件操作函数

python2下解决json的unicode编码问题

C语言读写文件的时候怎么控制字符编码方式?

怎样将unicode转化成中文

c++如何通过utf8字符串编码的文件名,在windows上打开一个文件

用C/C++写一个字符串GBK转UTF-8编码的函数,并写main函数测试(在线等)