Converting a string to an const unsigned char*

H

Hans Mull

Hi!
How can I convert a string to a const unsigned char*?
(string::c_str() converts the string to a signed char)

Thanks in advance, Hans
 
P

Pascal J. Bourguignon

Hans Mull said:
Hi!
How can I convert a string to a const unsigned char*?
(string::c_str() converts the string to a signed char)

Thanks in advance, Hans

#include <algorithm>
#include <string>

const unsigned char* convert(const std:string& s){
unsigned char* bytes=new[s.size()+1]();
std::copy(s.begin(),s.end(),bytes);
return(bytes);
}


If converting signed chars from the string into unsigned chars poses
problem, you may use transform instead of copy, passing a function
that will do the mapping you want between negative characters and
bytes.
 
J

Juha Nieminen

Hans said:
Hi!
How can I convert a string to a const unsigned char*?
(string::c_str() converts the string to a signed char)

The (bitwise) contents of the string don't change if the characters
are interpreted as unsigned chars instead of signed chars, so I'd say
it's completely safe to do this:

const unsigned char* us =
reinterpret_cast<const unsigned char*>(str.c_str());
 
P

peter koch

Hi!
How can I convert a string to a const unsigned char*?
(string::c_str() converts the string to a signed char)

As noted by Juha, a reinterpret_cast is safe and fine, but a question
is whether you must convert to unsigned char const * (I presume that
you want to preserve the constness!). Perhaps you should have used a
std::vector<unsigned char> or a std::basic_string<unsigned char> in
the first place?

/Peter
 
P

Puppet_Sock

As noted by Juha, a reinterpret_cast is safe and fine, but a question
is whether you must convert to unsigned char const * (I presume that
you want to preserve the constness!). Perhaps you should have used a
std::vector<unsigned char> or a std::basic_string<unsigned char> in
the first place?

The usual answer to questions such as that is "legacy code."
Socks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top