UNICODE字串與多位元組字串的轉換

來源:互聯網
上載者:User

一。先看一下兩個函數的聲明:

1. 多位元組字串與寬字元串的轉換
  int MultiByteToWideChar(
    UINT CodePage,         // code page,一般設為 CP_ACP
    DWORD dwFlags,         // character-type options,一般為設0
    LPCSTR lpMultiByteStr, // string to map,指向一個多位元組字串
    int cbMultiByte,       // number of bytes in string,多位元組字串的長度(位元組數,當以0結尾的時候,也可以設為-1)
    LPWSTR lpWideCharStr,  // wide-character buffer,存放轉換後的寬字元串緩衝區
    int cchWideChar        // size of buffer,寬字元串緩衝區的最大長度(字元數)
  );

1. 寬字元串與多位元組字串的轉換
  int WideCharToMultiByte(
    UINT CodePage,            // code page,一般設為 CP_ACP
    DWORD dwFlags,            // performance and mapping flags,一般為設0
    LPCWSTR lpWideCharStr,    // wide-character string,指向一個寬字元串
    int cchWideChar,          // number of chars in string,寬字元串的長度(字元數)
    LPSTR lpMultiByteStr,     // buffer for new string,存放轉換後的多位元組字串緩衝區
    int cbMultiByte,          // size of buffer,多位元組字串緩衝區的最大長度(位元組數)
    LPCSTR lpDefaultChar,     // default for unmappable chars,轉換失敗的字元所顯示的字串,一般設為NULL
    LPBOOL lpUsedDefaultChar  // set when default char used,如果有字元轉換失敗,則為TRUE,一般設為NULL
  );

2. 看一下用法:#include <STDLIB.H>#include <LOCALE.H>#include <Windows.h>int main(int argc, char* argv[]){setlocale(LC_ALL,"");    // 否則無法輸出中文char    ansiStr[] = "這是一個ANSI字串";printf( "ansiStr: %s\n", ansiStr );wchar_t wideStr[] = L"這是一個UNICODE字串";wprintf( L"wideStr: %s\n", wideStr );// 轉換ANSI字串到UNICODE字串int len = MultiByteToWideChar(CP_ACP, 0, ansiStr, -1, NULL, 0);  //
先取得轉換後的UNICODE字串所需的長度wchar_t* buf1 = (wchar_t*)calloc(len, sizeof(wchar_t));
        // 分配緩衝區MultiByteToWideChar(CP_ACP, 0, ansiStr, -1, buf1, len);    // 開始轉換wprintf(L"轉換後的UNICODE字串: %s\n", buf1);                 // 輸出轉換後的字串free(buf1);                                                                             // 釋放緩衝區// 轉換UNICODE字串到ANSI字串len = WideCharToMultiByte(CP_ACP, 0, wideStr, -1, NULL, 0, NULL, NULL);  //
先取得轉換後的ANSI字串所需的長度char* buf2 = (char*)calloc(len, sizeof(char)); 
                                           // 分配緩衝區WideCharToMultiByte(CP_ACP, 0, wideStr, -1, buf2, len, NULL, NULL);   //
開始轉換printf("轉換後的ANSI字串: %s\n", buf2);                                                 //
輸出轉換後的字串free(buf2);                                                                                                 //
釋放緩衝區return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.