MBS与Unicode字符的相互转换

本文主要介绍MBS与Unicode字符的相互转换

共有3种方法

  1. Windows API
  2. C API
  3. ATL中的转换宏

windows API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

//主要使用WideCharToMultiByte与MultiByteToWideChar这两个函数
string str="字符转换测试A";
wstring wstr=L"字符转换测试A";
/*宽字节转换为单字节
计算转换所需的字节数,包括NULL字符*/
int size1=WideCharToMultiByte(CP_ACP,0,wstr.c_str(),-1,NULL,0,NULL,false); //size为14
char *dest1=new char[size1];
WideCharToMultiByte(CP_ACP,0,wstr.c_str(),-1,dest1,size1,NULL,false);
cout<<dest1;
delete[] dest1
//单字节转换为宽字节
int size2=MultiByteToWideChar(CP_ACP,0,str.c_str(),-1,NULL,0); //size为8
WCHAR *dest2=new WCHAR[size2];
MultiByteToWideChar(CP_ACP,0,str.c_str(),-1,dest2,size2);
delete[] dest2

//其中CP_ACP与CP_OEMCP一样

C API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

//主要使用wcstombs与mbstowcs
//计算转换为单字节的长度(不含\0字符),只有中文字符可以这样算,中英混合长度就比实际大,
//对实际结果影响不大
int size1=wcstombs(NULL,wstr.c_str(),0)*2+1; //size为15
char *dest1=new char[size1];
setlocale(LC_ALL,""); //设置本地默认Locale
wcstombs(dest1,wstr.c_str(),size1);
setlocale(LC_ALL,"C"); //设置单字节
cout<<dest1;

//计算转换为宽字节的长度,可能比实际大
int size2=mbstowcs(NULL,str.c_str(),0)+1; //size为14
WCHAR *dest2=new WCHAR[size2];
setlocale(LC_ALL,""); //设置本地默认Locale
mbstowcs(dest2,str.c_str(),size2);
setlocale(LC_ALL,"W"); //设置宽字节
cout<<dest2;

ATL转投宏(最简单)

1
2
3
4
5
6
7
8
9
10

//CA2W 将单字节转换为宽字节
//CW2A 将宽宽限转换为单字节

CA2W str("hello, world");
WHCAR * str2=str;

CW2A str=L"hello, world";
char * str2=str;