简体   繁体   中英

converting string to array of bytes

I wanted to convert string into array of bytes . How can i do that?

Actually i wanted to read from the file and convert all that data into array of bytes .

If converted how can i obtain the size of that 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 );

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

char* bytes = str.c_str();

The length can be obtained through

int len = str.length();

The pointer can simply be casted to 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.

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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