Skip to content

Instantly share code, notes, and snippets.

@Tocchann
Created November 15, 2017 07:07
Show Gist options
  • Save Tocchann/345a2d1f428367749f588a1088765c8a to your computer and use it in GitHub Desktop.
Save Tocchann/345a2d1f428367749f588a1088765c8a to your computer and use it in GitHub Desktop.
std::string/wstring を使って、UNICODE と UTF-8 を相互変換(抜粋コード)
std::string ToUtf8Str( const wchar_t* value )
{
_ASSERTE( value != nullptr );
if( value == nullptr || *value == L'\0' ){
return "";
}
int needLength = WideCharToMultiByte( CP_UTF8, 0, value, -1, nullptr, 0, nullptr, nullptr );
if( needLength < 1 ){
return "";
}
std::string result;
result.resize( needLength-1 ); // \0を含むバイト数が返ってくる
WideCharToMultiByte( CP_UTF8, 0, value, -1, &result[0], needLength, nullptr, nullptr );
return result;
}
std::wstring ToUnicodeStr( const char* value )
{
_ASSERTE( value != nullptr );
if( value == nullptr || *value == '\0' ){
return L"";
}
int needLength = MultiByteToWideChar( CP_UTF8, 0, value, -1, nullptr, 0 );
std::wstring result;
result.resize( needLength-1 );
MultiByteToWideChar( CP_UTF8, 0, value, -1, &result[0], needLength );
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment