一个ASCII到UTF8的类

1.采用类方式

class a2w
{
    wchar_t* buffer;
  public:
     explicit a2w(const char* str):buffer(0)
    {
       if(str) {
           size_t nu = strlen(str);
           size_t n = ::MultiByteToWideChar(CP_ACP,0,(const char *)str,int(nu),NULL,0);
           buffer = new wchar_t[n+1];
          ::MultiByteToWideChar(CP_ACP,0,(const char *)str,int(nu),buffer,int(n));
      }
    }
  ~a2w() {  delete[] buffer;  }

  operator const wchar_t*() { return buffer; }

};

备注:

   explicit:用来修饰类的构造函数,表明该构造函数是显式的。主要防止这种类构造时被编译器自动换操作。

  

2.采用函数模式

/*

  wBuf 为申明指针即可。

*/

chr2wch(const char* buffer, wchar_t* wBuf)
{
      size_t len = strlen(buffer);

      size_t wlen = MultiByteToWideChar(CP_ACP, 0, (const char*)buffer, int(len), NULL, 0);

      wBuf = new wchar_t[wlen + 1];

      MultiByteToWideChar(CP_ACP, 0, (const_char*)buffer, int(len), wBuf, int(wlen));

}

 

 

//--------------------------------


随机文章:

LPWSTR ConvertLPCSTRToLPWSTR (char* pCstring)

{

LPWSTR pszOut = NULL;

if (pCstring != NULL)

{

int nInputStrLen = strlen (pCstring);

// Double NULL Termination

int nOutputStrLen = MultiByteToWideChar(CP_ACP, 0, pCstring, nInputStrLen, NULL, 0) + 2;

pszOut = new WCHAR [nOutputStrLen];

if (pszOut)

{

memset (pszOut, 0x00, sizeof (WCHAR)*nOutputStrLen);

MultiByteToWideChar (CP_ACP, 0, pCstring, nInputStrLen, pszOut, nInputStrLen);

}

}

return pszOut;

}

 

After using this method do remember to delete the allocated string.

 

eg:

 

char * str = new char[strlen("ASHOK") + 1];

strcpy(str, "ASHOK");

WCHAR * pwStr = ConvertLPCSTRToLPWSTR(str);

//Use this pwStr

......

.....

//delete the wide char pointer.

delete []pwStr;

 

//--------------------------

wstring MultCHarToWideChar(string str)
{
    //获取缓冲区的大小,并申请空间,缓冲区大小是按字符计算的
    int len=MultiByteToWideChar(CP_ACP,0,str.c_str(),str.size(),NULL,0);
    TCHAR *buffer=new TCHAR[len+1];
    //多字节编码
换成宽字节编码
    MultiByteToWideChar(CP_ACP,0,str.c_str(),str.size(),buffer,len);
    buffer[len]='/0';//添加字符串结尾
    //删除缓冲区并返回值
    wstring return_value;
    return_value.append(buffer);
    delete []buffer;
    return return_value;
}
string WideCharToMultiChar(wstring str)
{
    string return_value;
    //获取缓冲区的大小,并申请空间,缓冲区大小是按字节计算的
    int len=WideCharToMultiByte(CP_ACP,0,str.c_str(),str.size(),NULL,0,NULL,NULL);
    
char *buffer=new char
[len+1];
    WideCharToMultiByte(CP_ACP,0,str.c_str(),str.size(),buffer,len,NULL,NULL);
    buffer[len]='/0';
    //删除缓冲区并返回值
    return_value.append(buffer);
    delete []buffer;
    return return_value;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值