Contents
Như các bạn đã biết, kiểu multibyte là kiểu char*, kích thước mỗi phần tử của mảng char là: sizeof(char) = 1 byte. Trong khi đó, kích thước của phần tử mảng wchar_t là 2 byte. Dưới đây, tôi sẽ giới thiệu đến các bạn các cách convert từ wchar sang multibyte và ngược lại.
Convert wchar sang multibyte
Sử dụng hàm wcstombs()
Ví dụ: sử dụng hàm wcstombs() convert wchar sang multibyte
#include <stdio.h> /* printf */ #include <stdlib.h> /* wcstombs, wchar_t(C) */ #include "conio.h" void main() { const wchar_t str[] = L"vncoding.net"; char buffer[32]; int ret; printf ("wchar_t string: %ls \n", str); ret = wcstombs(buffer, str, sizeof(buffer)); if (ret == 32) buffer[31] = '\0'; if (ret) printf ("multibyte string: %s \n", buffer); getch(); }
Kết quả:
Sử dụng hàm WideCharToMultiByte()
Ví dụ: sử dụng hàm WideCharToMultiByte( ) convert wchar sang multibyte
#include <stdio.h> /* printf */ #include <stdlib.h> /* malloc() */ #include "conio.h" /* getch()*/ #include <windows.h> /* WideCharToMultiByte*/ void main() { const wchar_t str[] = L"vncoding.net"; char* mbBuf; int ret; printf ("wchar_t string: %ls \n", str); int nChars = WideCharToMultiByte(CP_ACP, 0, str, -1, 0, 0, NULL, NULL); mbBuf = (char*)malloc(nChars); if (mbBuf) { memset(mbBuf, 0x00, nChars); WideCharToMultiByte(CP_ACP, 0, str, -1, mbBuf, nChars, NULL, NULL); printf ("multibyte string: %s \n", mbBuf); free(mbBuf); } getch(); }
Kết quả:
Convert multibyte sang widechar
Sử dụng hàm mbstowcs()
Ví dụ:
#include <stdio.h> /* printf */ #include <stdlib.h> /* malloc() */ #include "conio.h" /* getch()*/ void main() { const char str[] = "vncoding.net"; wchar_t wcBuf[32]; int ret; printf ("multibyte string: %s \n", str); ret = mbstowcs( wcBuf, str, sizeof(wcBuf) ); if (ret == 32) wcBuf[31] = '\0'; if (ret) printf ("wchar_t string: %ls \n", wcBuf); getch(); }
Kết quả:
Sử dụng hàm MultiByteToWideChar()
Ví dụ:
#include <stdio.h> /* printf */ #include <stdlib.h> /* malloc() */ #include "conio.h" /* getch()*/ #include <windows.h> /* WideCharToMultiByte*/ #include "wchar.h" /* wmemset*/ void main() { const char str[] = "vncoding.net"; wchar_t* wcBuf; int ret; printf ("multibyte string: %s \n", str); //nChars: the number of character int nChars = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0); wcBuf = (wchar_t*)malloc(nChars*sizeof(wchar_t)); if (wcBuf) { wmemset(wcBuf, 0x00, nChars); MultiByteToWideChar(CP_ACP, 0, str, -1, (LPWSTR)wcBuf, nChars); printf ("wchar_t string: %ls \n", wcBuf); free(wcBuf); } getch(); }
Kết quả:
Leave a Reply
You must be logged in to post a comment.