프로그래밍 언어/C++

[C++] 문자열 인코딩 (유니코드 멀티바이트 UTF-8 변환)

ShovelingLife 2023. 8. 10. 18:42

유니코드 > 멀티바이트

wchar_t strUnicode[256] = {0,};
char	strMultibyte[256] = {0,};
wcscpy_s(strUnicode,256,L"유니코드");
int len = WideCharToMultiByte( CP_ACP, 0, strUnicode, -1, NULL, 0, NULL, NULL );	
WideCharToMultiByte( CP_ACP, 0, strUnicode, -1, strMultibyte, len, NULL, NULL );

stl 이용

wstring strUni = L"유니코드";
int len = WideCharToMultiByte( CP_ACP, 0, &strUni[0], -1, NULL, 0, NULL, NULL );
string strMulti(len,0);
WideCharToMultiByte( CP_ACP, 0,  &strUni[0], -1, &strMulti[0], len, NULL, NULL );

멀티바이트 > 유니코드

wchar_t strUnicode[256] = {0,};
char	strMultibyte[256] = {0,};
strcpy_s(strMultibyte,256,"멀티바이트");
int nLen = MultiByteToWideChar(CP_ACP, 0, strMultibyte, strlen(strMultibyte), NULL, NULL);
MultiByteToWideChar(CP_ACP, 0, strMultibyte, strlen(strMultibyte), strUnicode, nLen);

stl 이용

string strMulti = "멀티바이트";	
int nLen = MultiByteToWideChar(CP_ACP, 0, &strMulti[0], strMulti.size(), NULL, NULL);
wstring strUni(nLen,0);
MultiByteToWideChar(CP_ACP, 0, &strMulti[0], strMulti.size(), &strUni[0], nLen);

유니코드 > utf-8

wchar_t strUni[256] =L"유니코드";
char strUtf8[256] ={0,};
int nLen = WideCharToMultiByte(CP_UTF8, 0, strUni, lstrlenW(strUni), NULL, 0, NULL, NULL);
WideCharToMultiByte (CP_UTF8, 0, strUni, lstrlenW(strUni), strUtf8, nLen, NULL, NULL);

utf-8 > 유니코드

wchar_t strUnicode[256] = {0,};
char	strUTF8[256] = {0,};
strcpy_s(strUTF8,256,"utf-8글자..");// 이건 사실 멀티바이트지만 UTF8이라고 생각해주세요 -_-;;
int nLen = MultiByteToWideChar(CP_UTF8, 0, strUTF8, strlen(strUTF8), NULL, NULL);
MultiByteToWideChar(CP_UTF8, 0, strUTF8, strlen(strUTF8), strUnicode, nLen);

기본적으로 UTF-8로 변형할땐 유니코드 상태에서만 변형을 시켜야 된다

 만약 멀티 바이트를 UTF-8로 변형하고 싶을때에는
   멀티바이트 -> 유니코드(UTF-16) -> UTF-8 
UTF-8을 멀티바이트로 변형할때에는
   UTF-8 -> 유니코드(UTF-16) -> 멀티바이트..
 

 

#include <atlstr.h> // MFC사용안하고도 CString를 사용할수 있다

void main()
{
  wstring strUni = CA2W("멀티바이트를 유니코드로 변환");
  string strMulti = CW2A(L"유니코드를 멀티바이트로 변환");
  string strUTF8 = CW2A(L"유니코드를 UTF8로변환",CP_UTF8);
  //string에서 포인터 얻어오는게 c_str()
  //CA2W나 CW2A에서 포인터 얻어오는건 m_psz
  //그리고 CA2W CW2A는 기본적으로 CString 즉 (CAtlString)에 기반을 두고 고 있기때문에.
  // CString를 사용할때 가장 빠른다!!.
  // 멀티 플랫폼을 기준으로 한다면 CA2W는 사용 못함!
}

 

https://icartsh.tistory.com/13