Converting a string to an const unsigned char*

Discussion in 'C++' started by Hans Mull, Apr 21, 2008.

  1. Hans Mull

    Hans Mull Guest

    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
     
    Hans Mull, Apr 21, 2008
    #1
    1. Advertisements

  2. #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.
     
    Pascal J. Bourguignon, Apr 21, 2008
    #2
    1. Advertisements

  3. 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());
     
    Juha Nieminen, Apr 21, 2008
    #3
  4. Hans Mull

    peter koch Guest

    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
     
    peter koch, Apr 21, 2008
    #4
  5. Hans Mull

    Puppet_Sock Guest

    The usual answer to questions such as that is "legacy code."
    Socks
     
    Puppet_Sock, Apr 21, 2008
    #5
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.