1

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.

1
  • You want to change "Hello world" string to array of bytes? Commented Jul 13, 2011 at 18:53

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

5 Comments

c_str() returns a const char *, casting away constness probably wouldnt cause any problems as long as you're sure the string data is modifiable, but I dont like doing it...just in case.
You wont get something other than const char* out of the string, and copying it over seems to be overkill.
what about &myString[0] ? - im not 100% sure if the memory is always contiguous come to think of it. do you know?
@Node: Every popular implementation now has contiguous storage for std::string, and the C++0x standard will guarantee it.
What about using the string::data() method?
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.