396,093 Members | 3,558 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 396,093 IT Pros & Developers. It's quick & easy.

String --> Byte array

qazmlp
P: n/a
How can string be converted into a byte array in C++ ?
Can I used std::bitset<> to do it ?
Jul 19 '05 #1
Share this Question
Share on Google+
4 Replies


Ron Natalie
P: n/a

"qazmlp" <qazmlp1209@rediffmail.com> wrote in message news:db9bbf31.0308260522.58e07e63@posting.google.c om...
How can string be converted into a byte array in C++ ?
Can I used std::bitset<> to do it ?


Yoiu can just call data() to get a transient const char* that points
to the beginning of a character array. Alternatively, you can copy
it to a vector:

string s = ...

vector<char> v(s.size());
copy(s.begin(), s.end(), v.begin());
Jul 19 '05 #2

Mike Wahler
P: n/a

qazmlp <qazmlp1209@rediffmail.com> wrote in message
news:db9bbf31.0308260522.58e07e63@posting.google.c om...
How can string be converted into a byte array in C++ ?
Can I used std::bitset<> to do it ?


std::string s("Hello");
char *array = new char[s.size()];
std::copy(s.begin(), s.end(), array, array + s.size());
/* etc */
delete [] array;

-Mike

Jul 19 '05 #3

Gianni Mariani
P: n/a
qazmlp wrote:
How can string be converted into a byte array in C++ ?
Can I used std::bitset<> to do it ?


A string IS an array of 'string::value_type' underneath.

Why do you need to convert it ?

Here is an example - you can use the method
"data()" and return a const char *

Or, why not just use iterators as arrays ? (second example).

#include <iostream>
#include <string>
int main()
{
std::string foo( "ABC" );

//examp 1
const char * array = foo.data();

array[0] + array[2];

//examp 2
std::string::iterator iter_array = foo.begin();

iter_array[ 2 ] = 'x';

std::cout << foo << '\n';

}
Jul 19 '05 #4

Chris \( Val \)
P: n/a

"Ron Natalie" <ron@sensor.com> wrote in message
news:3f4b6a34$0$23182$9a6e19ea@news.newshosting.co m...
|
| "qazmlp" <qazmlp1209@rediffmail.com> wrote in message
news:db9bbf31.0308260522.58e07e63@posting.google.c om...
| > How can string be converted into a byte array in C++ ?
| > Can I used std::bitset<> to do it ?
|
| Yoiu can just call data() to get a transient const char* that points
| to the beginning of a character array. Alternatively, you can copy
| it to a vector:
|
| string s = ...
|
| vector<char> v(s.size());
| copy(s.begin(), s.end(), v.begin());

Alternatively:

vector<char> v( s.begin(), s.end() );

Cheers.
Chris Val
Jul 19 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.