3

I need to process the data stored in wide strings at a low level. I am able to convert to a vector of Bytes with the following method:

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);

However, I am having trouble going the other way; I am not very familiar with casting. How do I convert a vector of Bytes to a wstring?

Dia McThrees
  • 261
  • 2
  • 7

2 Answers2

4
#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() );
}
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • 1
    +1 for the great answer. One question though: I am using these method on Ubuntu 16.04 with g++ 5.4.0 - Isn't it requires to compile with C++11 and the header file `` ? Thanks !! – Guy Avraham Mar 12 '18 at 17:45
  • 1
    @GuyAvraham Good question, but honestly I'm not familiar with Ubuntu. – Rabbid76 Mar 12 '18 at 21:11
3

You could do it like this
mystring.assign(reinterpret_cast<wstring::const_pointer>(&byteVector[0]), byteVector.size() / sizeof(wstring::value_type));

Slava Zhuyko
  • 691
  • 4
  • 12