// 인코딩을 직접 바꾸는 것은 어려우므로, UTF-16으로 바꾼 다음에 원하는 인코딩으로 다시 바꾸게 했습니다.
// 참고로, MultiByteToWideChar 함수의 cbMultiByte 인자와 WideCharToMultiByte 함수의 cchWideChar 인자를 -1로 넘겨 주는 게 더
// 편합니다. 하지만 그러면 공문자까지 변환이 되므로, outEncodingText에 공문자가 포함되서 const char*와 호환되지 않는 문제가
// 생깁니다. 그래서 할 수 없이 입력 문자열의 크기도 넘겨 주게 했습니다.
string convert_encoding(UINT in_encoding, UINT out_encoding, const string& in_encoding_text)
{
// 인코딩을 in_encoding에서 UTF-16으로 변환합니다.
int utf16_character_count = MultiByteToWideChar(in_encoding, 0, in_encoding_text.c_str(), in_encoding_text.size(), NULL, 0);
if (utf16_character_count == 0)
return "";
wstring utf16_text(utf16_character_count, L'\0');
MultiByteToWideChar(in_encoding, 0, in_encoding_text.c_str(), in_encoding_text.size(), &utf16_text[0], utf16_character_count);
// 인코딩을 UTF-16에서 out_encoding으로 변환합니다.
int utf8_character_count = WideCharToMultiByte(out_encoding, 0, &utf16_text[0], utf16_text.size(), NULL, 0, NULL, NULL);
if (utf8_character_count == 0)
return "";
string out_encoding_text(utf8_character_count, '\0');
WideCharToMultiByte(out_encoding, 0, &utf16_text[0], utf16_text.size(), &out_encoding_text[0], utf8_character_count, NULL, NULL);
return out_encoding_text;
}
string convert_from_ansi_to_utf8(const string& text)
{
return convert_encoding(CP_ACP, CP_UTF8, text);
}
string convert_from_utf8_to_ansi(const string& text)
{
return convert_encoding(CP_UTF8, CP_ACP, text);
}
댓글을 달아 주세요