티스토리 뷰
구글에서 검색을 조금 하다보면 손쉽게 CT2CW() 라던가, CT2W() 같은 매크로를 사용하면 된다는
글을 많이 볼 수 있는데, 아래와 같은 방법으로 사용하면 된다.
wstring strUni = CA2W("멀티바이트를 유니코드로 변환");
string strMulti = CW2A(L"유니코드를 멀티바이트로 변환");
string strUTF8 = CW2A(L"유니코드를 UTF8로변환",CP_UTF8);
(참고로 LPCWSTR은 유니코드고, CString은 프로젝트 설정에 따라 바뀐다.)
그러나 종종 알 수 없는 이유로 (내가 모르는 것일 뿐...) 위 방법으로 변환이되지 않는 경우가 있다.
그럴 경우 MultiByteToWideChar 를 사용하면 된다.
* 함수 원형
int MultiByteToWideChar(uCodePage, dwFlags, lpMultiByteStr,
cchMultiByte, lpWideCharStr, cchWideChar)
UINT uCodePage; /* codepage */
DWORD dwFlags; /* character-type options */
LPCSTR lpMultiByteStr; /* address of string to map */
int cchMultiByte; /* number of characters in string */
LPWSTR lpWideCharStr; /* address of wide-character buffer */
int cchWideChar; /* size of wide-character buffer */
* 사용법 (출처: http://myblue0324.tistory.com/15)
1) 유니코드 -> 멀티바이트
char* ConvertUnicodeToMultybyte(CString strUnicode)
{
int nLen = WideCharToMultiByte(CP_ACP, 0, strUnicode, -1, NULL, 0, NULL, NULL);
char* pMultibyte = new char[nLen];
memset(pMultibyte, 0x00, (nLen)*sizeof(char));
WideCharToMultiByte(CP_ACP, 0, strUnicode, -1, pMultibyte, nLen, NULL, NULL);
return pMultibyte;
}
2) 멀티바이트 -> 유니코드
CString ConvertMultibyteToUnicode(char* pMultibyte)
{
int nLen = strlen(pMultibyte);
WCHAR *pWideChar = new WCHAR[nLen];
memset(pWideChar, 0x00, (nLen)*sizeof(WCHAR));
MultiByteToWideChar(CP_ACP, 0, (LPCSTR)pMultibyte, -1, pWideChar, nLen);
CString strUnicode;
strUnicode.Format(_T("%s"), pWideChar);
delete [] pWideChar;
return strUnicode;
}
3) 사용예시
CString strUnicode(_T("유니코드"));
char* pMultibyte = ConvertUnicodeToMultibyte(strUnicode);
char* pMultibyte = "멀티바이트";
CString strUnicode = ConvertMultibyteToUnicode(pMultibyte);
'C++' 카테고리의 다른 글
[C++11] std::regex를 사용해 보자. (0) | 2017.11.27 |
---|---|
윈속 초기화 WSAStartup (0) | 2017.11.27 |
간단한 루프 병렬화(vs2017) (0) | 2017.11.12 |
간단한 시간 재기 (0) | 2017.11.12 |
윈도우용 OpenSSL 라이브러리 사용하기(feat. vs2015) (2) | 2017.01.13 |