Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ convert between Byte vector and wstring

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?

like image 550
Dia McThrees Avatar asked Jul 30 '26 10:07

Dia McThrees


2 Answers

#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() );
}
like image 200
Rabbid76 Avatar answered Jul 31 '26 23:07

Rabbid76


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

like image 40
Slava Zhuyko Avatar answered Jul 31 '26 23:07

Slava Zhuyko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!