简体   繁体   English

将字符串转换为字节数组

[英]converting string to array of bytes

I wanted to convert string into array of bytes .我想将string转换为bytes array How can i do that?我怎样才能做到这一点?

Actually i wanted to read from the file and convert all that data into array of bytes .实际上我想从文件中读取并将所有数据转换为bytes array

If converted how can i obtain the size of that array ?如果转换后如何获得该array的大小?

After obtaining array of bytes i wanted to get the pointer of type LPVOID and make it point to that array of bytes, to use the function BOOL WritePrinter( __in HANDLE hPrinter, __in LPVOID pBuf, __in DWORD cbBuf, __out LPDWORD pcWritten );获得字节数组后,我想获取LPVOID类型的指针并使其指向该字节数组,以使用 function BOOL WritePrinter( __in HANDLE hPrinter, __in LPVOID pBuf, __in DWORD cbBuf, __out LPDWORD pcWritten );

The second argument demands pointer towards array of bytes.第二个参数需要指向字节数组的指针。 But i don't know any method that does this.但我不知道有什么方法可以做到这一点。

You can convert a string to a char* using您可以使用将string转换为char*

char* bytes = str.c_str();

The length can be obtained through长度可以通过

int len = str.length();

The pointer can simply be casted to LPVOID指针可以简单地转换为LPVOID

LPVOID ptr = (LPVOID) bytes;

You can access the data in the std::string by calling the std::string::data() member function, that will return a const char* , alternatively you can just use std::string::operator[] to manipulate the std::string as if it were a char array.您可以通过调用std::string::data()成员 function 来访问std::string中的数据,这将返回一个const char* ,或者您可以只使用std::string::operator[]来操作std::string就好像它是一个 char 数组一样。

If you want it as a vector, you can create one with:如果你想把它作为一个向量,你可以创建一个:

std::vector<char> myVector(myString.beging(), myString.end());
char *myCharPtr = &myVector.front();

Edit: This is probably the quickest/easier way...编辑:这可能是最快/更简单的方法......

std::string myStr = "testing";
char *myCharPtr = &myStr[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM