wchar_t 与 char 的互相转换

http://haofu123.blog.163.com/blog/static/178294920096243161997/

//将wchar_t* 转成char*的实现函数如下:

char *w2c(char *pcstr,const wchar_t *pwstr, size_t len)

{

int nlength=wcslen(pwstr);

//获取转换后的长度

int nbytes = WideCharToMultiByte( 0, // specify the code page used to perform the conversion

0,         // no special flags to handle unmapped characters

pwstr,     // wide character string to convert

nlength,   // the number of wide characters in that string

NULL,      // no output buffer given, we just want to know how long it needs to be

0,

NULL,      // no replacement character given

NULL );    // we don't want to know if a character didn't make it through the translation

// make sure the buffer is big enough for this, making it larger if necessary

if(nbytes>len)   nbytes=len;

// 通过以上得到的结果,转换unicode 字符为ascii 字符

WideCharToMultiByte( 0, // specify the code page used to perform the conversion

0,         // no special flags to handle unmapped characters

pwstr,   // wide character string to convert

nlength,   // the number of wide characters in that string

pcstr, // put the output ascii characters at the end of the buffer

nbytes,                           // there is at least this much space there

NULL,      // no replacement character given

NULL );

return pcstr ;

}

//将char* 转成wchar_t*的实现函数如下:

//这是把asii字符转换为unicode字符,和上面相同的原理

void c2w(wchar_t *pwstr,size_t len,const char *str)

{

if(str)

    {

      size_t nu = strlen(str);

      size_t n =(size_t)multibytetowidechar(cp_acp,0,(const char *)str,(int)nu,null,0);

      if(n>=len)n=len-1;

      multibytetowidechar(cp_acp,0,(const char *)str,(int)nu,pwstr,(int)n);

   pwstr[n]=0;

    }

}

wchar_t *  charToWchar(wchar_t  * pwstring,  const   char   * str)

{

wchar_t
*  temp=NULL;

if (str)

    {

      int charlength 
=  strlen(str);

      int n 
= (int)MultiByteToWideChar(CP_ACP, 0 ,( const   char   * )str, int (charlength),NULL, 0 );


      temp
=   new  wchar_t[n + 1 ];

   ::MultiByteToWideChar(CP_ACP,
0 ,( const   char   * )str, int (nu),buffer, int (n));    

   }

return  buffer;

delete buffer;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值