How to convert wstring into byte vector

ST3 picture ST3 · Aug 20, 2013 · Viewed 7.9k times · Source

Hi I have a few typedefs:

typedef unsigned char Byte;
typedef std::vector<Byte> ByteVector;
typedef std::wstring String;

I need to convert String into ByteVector, I have tried this:

String str = L"123";
ByteVector vect(str.begin(), str.end());

As a result vectror contains 3 elements: 1, 2, 3. However it is wstring so every charcter in this string is wide so my expected result would be: 0, 1, 0, 2, 0, 3.

Is there any standart way to do that or I need to write some custom function.

Answer

jrok picture jrok · Aug 20, 2013
Byte const* p = reinterpret_cast<Byte const*>(&str[0]);
std::size_t size = str.size() * sizeof(str.front());
ByteVector vect(p, p+size);