Ascii utf8 Unicode 字符串转换

来源:互联网 发布:mysql 5.6.25.tar.gz 编辑:程序博客网 时间:2024/06/10 05:05

简介

    最近在做Sqlite相关代码,发现Sqlite只支持utf_8字符集,因此需要unicode/ascii到utf_8的转换,因此记录下一下代码,方便一会重用;

linux下支持并未编写,因此用 static_assert(false)阻止编译通过

代码

std::string BLES_EXPORT AsciiToUtf8( const std::string& aStr ){//先把 ascii 转为 unicode std::wstring wstr = AsciiToUnicode( aStr );//最后把 unicode 转为 utf8return UnicodeToUtf8(wstr);}std::string BLES_EXPORT UnicodeToAscii( const std::wstring wStr ){std::string resultstring;#ifdef SC_WINint widesize = WideCharToMultiByte (CP_ACP, 0, wStr.c_str(), -1, NULL, 0, NULL, NULL );assert( 0 != widesize );resultstring.resize(widesize);int convresult = ::WideCharToMultiByte(CP_ACP, 0, wStr.c_str(), -1, (char*)resultstring.c_str(), widesize, NULL, NULL);assert( convresult == widesize );#elsestatic_assert( 0 );#endifreturn resultstring;}std::string BLES_EXPORT Utf8ToAscii( const std::string& utf8Str ){std::wstring wstr = Utf8ToUnicode( utf8Str );return UnicodeToAscii( wstr );}std::wstring BLES_EXPORT Utf8ToUnicode( const std::string& utf8Str ){std::wstring resultstring;#ifdef SC_WINint widesize = MultiByteToWideChar (CP_ACP, 0, (char*)utf8Str.c_str(), -1, NULL, 0);assert( widesize != ERROR_NO_UNICODE_TRANSLATION &&0 != widesize );resultstring.resize(widesize);int convresult = MultiByteToWideChar (CP_ACP, 0, (char*)utf8Str.c_str(), -1, (wchar_t*)resultstring.c_str(), widesize);assert( convresult == widesize );#elsestatic_assert( 0 );#endifreturn resultstring;}



 

原创粉丝点击