您的位置:首页 > 其它

宽字符和ASCII码字符的转换

2013-10-07 20:57 183 查看
二.宽字符与ASCII的转换

 

比较多的是用Windows的API,MultiByteToWideChar 跟WideCharToMultiByte 来实现宽字符跟ASCII之间的转换。

看这段代码.

 

#include<windows.h>
#include <iostream>
using namespace std;
int main()
{
wchar_t wText[] = {L"宽字符转换实例!OK!"};
int i;
cout<<sizeof(wText)<<endl;     //宽字符占的字节数,24字节
DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,wText,-1,NULL,0,NULL,FALSE);  //获取宽字符数组wText转为ASCII需要的字节
cout<<dwNum<<endl;            //dwNum 长度为19字节
char *psText;
psText = new char[dwNum];
WideCharToMultiByte (CP_OEMCP,NULL,wText,-1,psText,dwNum,NULL,FALSE);     //把宽字符转为ASCII,写入psText 开始的内存
cout<<psText<<endl;
delete []psText;
system("pause");
return 0;
}


 

上面这段代码可以实现从宽字符转为ASCII字符。

 

#include<windows.h>
#include <iostream>
using namespace std;
int main()
{
char sText[] = {"多字节字符串!OK!"};
cout<<sizeof(sText)<<endl;     //ASCII字符占用17字节,包括'/0'
DWORD dwNum = MultiByteToWideChar (CP_ACP, 0, sText, -1, NULL, 0);
cout<<dwNum<<endl;    //转换该ASCII字符串需要宽字符个数为11,'/0'也被转为宽字符
wchar_t *pwText;
pwText = new wchar_t[dwNum];
MultiByteToWideChar (CP_ACP, 0, sText, -1, pwText, dwNum);           //进行转换
setlocale(LC_ALL,   "");    //因为要输出宽字符,设置一下
wcout<<pwText<<endl;   //输出宽字符,注意要用wcout
delete []pwText;
system("pause");
return 0;
}


 
 
上面这段代码可以实现从ASCII字符转为宽字符。

 

 

 

至此,大家应该对宽字符Unicode跟ASCII多字节编码有大体认识了吧。

最后,为了方便程序移植,写两个函数版的转换:

 

char* convert(const WCHAR *str)
{
DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,str,-1,NULL,0,NULL,FALSE);  //获取宽字符数组wText转为ASCII需要的字节
char *psText;
psText = new char[dwNum];
WideCharToMultiByte (CP_OEMCP,NULL,str,-1,psText,dwNum,NULL,FALSE);     //把宽字符转为ASCII,写入psText 开始的内存
return psText;
}
WCHAR* nw_convert(const char *str)
{
DWORD dwNum = MultiByteToWideChar (CP_ACP, 0, str, -1, NULL, 0);
wchar_t *pwText;
pwText = new wchar_t[dwNum];
MultiByteToWideChar (CP_ACP, 0, str, -1, pwText, dwNum);           //进行转换
return pwText;
}


 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: