C语言接收消息乱码问题

来源:互联网 发布:鸡啄米 mfc编程入门 编辑:程序博客网 时间:2024/05/01 08:56

VS的预处理使用的是ANSI编码,而安卓网络数据都是UTF8格式的,这样直接使用printf打印出出来的当然是乱码,所以解决方法就是把UFT8格式的数据转换成ANSI!

//UTF8转成Unicode
wchar_t * UTF8ToUnicode( const char* str )
{
int textlen = 0;
wchar_t * result;
textlen = MultiByteToWideChar( CP_UTF8, 0, str,-1, NULL,0 );
result = (wchar_t *)malloc((textlen+1)*sizeof(wchar_t));
memset(result,0,(textlen+1)*sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0,str,-1,(LPWSTR)result,textlen );
return result;
}

//Unicode转成ANSI
char * UnicodeToANSI( const wchar_t *str )
{
char * result;
int textlen = 0;
// wide char to multi char
textlen = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
result =(char *)malloc((textlen+1)*sizeof(char));
memset( result, 0, sizeof(char) * ( textlen + 1 ) );
WideCharToMultiByte( CP_ACP, 0, str, -1, result, textlen, NULL, NULL );
return result;
}这里写代码片

0 0