一。先看一下兩個函數的聲明:
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;}