[英]Convert string into byte array
I was wondering if there was a C++ equivalent to Javas .getBytes() method.我想知道是否有 C++ 等效于 Javas .getBytes()方法。 I'm reading a .txt file and need to convert each line into bytes.我正在阅读一个 .txt 文件,需要将每一行转换为字节。
Thanks in advance!提前致谢!
In C++ a char
is a byte.在 C++ 中, char
是一个字节。 And so a std::string
is already a sequence of bytes.所以std::string
已经是一个字节序列。
However, you may want a sequence of unsigned char
.但是,您可能需要一个unsigned char
序列。
One way is to just copy the byte values from the string, eg into a std::vector
:一种方法是从字符串中复制字节值,例如复制到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, eg using a wide stream, then the bytes depend on your preferred encoding of that string.如果您将文本文件读入每行std::wstring
,例如使用宽流,则字节取决于您对该字符串的首选编码。
In practice, except possibly on an IBM mainframe, a C++ wide string is either UTF-16 or UTF-32 encoded.实际上,除了可能在 IBM 大型机上之外,C++ 宽字符串是 UTF-16 或 UTF-32 编码的。 For these two encodings the standard library provides specializations of std::codecvt
that can convert to and from UTF-8.对于这两种编码,标准库提供了std::codecvt
,可以与 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.如果您想从宽字符串中进行任意编码,那么就 C++ 标准库而言,您就不走运了,抱歉。
std::string::data 是等价的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.