ASC编码和Unicode编码之间转换

1. ASC编码转Unicode编码

 

void ConvertMultiToWide(LPCSTR lpstr, int size, CStringW& csWide)
{
    //计算字符长度
   int nCount = MultiByteToWideChar(CP_ACP, 0, lpstr, size, NULL, 0);
    //分配内存
   wchar_t* sConver = new wchar_t[nCount + 1];
    SecureZeroMemory(sConver, _countof(sConver));
    //转换
   MultiByteToWideChar(CP_ACP, 0, lpstr, size, sConver, nCount);
    csWide.Empty();
    csWide.Format(_T("%s"), sConver);
    delete[] sConver;
}

 

 

void ConvertMultiToWide(LPCSTR lpstr, CStringW& csWide)
{
    CStringA csMulti(lpstr);
    csWide.Empty();

    int iStrLen = MultiByteToWideChar(CP_ACP, 0, 
        csMulti.GetBuffer(), csMulti.GetLength(), 
        NULL, 0);
    MultiByteToWideChar(CP_ACP, 0, 
        csMulti.GetBuffer(), csMulti.GetLength(), 
        csWide.GetBuffer(iStrLen), iStrLen);

    csMulti.ReleaseBuffer();
    csWide.ReleaseBuffer(iStrLen);
}

 

 

2. Unicode编码转ASC编码

 

void ConvertWideToMulti(LPCWSTR lpwstr, CStringA& csMulti)
{
    CStringW csWide(lpwstr);
    csMulti.Empty();

    int iStrLen = WideCharToMultiByte(CP_UTF8, 0, 
        csWide.GetBuffer(), csWide.GetLength(), 
        NULL, 0, 
        NULL, NULL);
    WideCharToMultiByte(CP_UTF8, 0,
        csWide.GetBuffer(),csWide.GetLength(),
        csMulti.GetBuffer(iStrLen), iStrLen,
        NULL, NULL);

    csWide.ReleaseBuffer();
    csMulti.ReleaseBuffer(iStrLen);
}

 

你可能感兴趣的:(ASC编码和Unicode编码之间转换)