I was wondering if there was a C++ equivalent to Javas .getBytes() method. I'm reading a .txt file and need to convert each line into bytes.
Thanks in advance!
I was wondering if there was a C++ equivalent to Javas .getBytes() method. I'm reading a .txt file and need to convert each line into bytes.
Thanks in advance!
In C++ a char
is a byte. And so a std::string
is already a sequence of bytes.
However, you may want a sequence of unsigned char
.
One way is to just copy the byte values from the string, e.g. into a std::vector
:
using Byte = unsigned char;
vector<Byte> const bytes( s.begin(), s.end() );
If you're reading the text file into a std::wstring
per line, e.g. using a wide stream, then the bytes depend on your preferred encoding of that string.
In practice, except possibly on an IBM mainframe, a C++ wide string is either UTF-16 or UTF-32 encoded. For these two encodings the standard library provides specializations of std::codecvt
that can convert to and from UTF-8.
If you want an arbitrary encoding from a wide string, then you're out of luck as far as the C++ standard library is concerned, sorry.
std::string::data is the equivalent.