宽字符和ASCII码字符的转换

二.宽字符与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;  
}


 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值