我需要以较低的级别处理存储在宽字符串中的数据。我可以使用以下方法转换为vector
Bytes
:
typedef unsigned char Byte;
wstring mystring = L"my wide string";
Byte const *pointer = reinterpret_cast<Byte const*>(&mystring[0]);
size_t size = mystring.size() * sizeof(mystring.front());
vector<Byte> byteVector(pointer, pointer + size);
然而,我却遇到了麻烦;我对铸造不是很熟悉。如何将vector
Bytes
转换为wstring
?
答案 0 :(得分:3)
#include <string>
#include <codecvt>
std::wstring wstring_convert_from_char( const char *str )
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter;
return converter.from_bytes( str );
}
std::string string_convert_from_wchar( const wchar_t *str )
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter;
return converter.to_bytes( str );
}
std::wstring wstring_convert_from_bytes( const std::vector< char > &v )
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter;
return converter.from_bytes( v.data(), v.data() + v.size() );
}
std::vector< char > wstring_convert_to_bytes( const wchar_t *str )
{
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter;
std::string string = converter.to_bytes( str );
return std::vector< char >( string.begin(), string.end() );
}
答案 1 :(得分:3)
你可以这样做
mystring.assign(reinterpret_cast<wstring::const_pointer>(&byteVector[0]), byteVector.size() / sizeof(wstring::value_type));