3

我需要在低级别处理存储在宽字符串中的数据。我可以使用以下方法转换为vectorof :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);

但是,我在走另一条路时遇到了麻烦;我对选角不是很熟悉。如何将 a 转换vectorBytesa wstring

4

2 回答 2

3

你可以这样做
mystring.assign(reinterpret_cast<wstring::const_pointer>(&byteVector[0]), byteVector.size() / sizeof(wstring::value_type));

于 2016-01-09T21:15:56.257 回答
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() );
}
于 2015-12-06T08:15:39.947 回答