Get bytes from std::string in C++

后端 未结 7 1248
遇见更好的自我
遇见更好的自我 2020-12-08 14:12

I\'m working in a C++ unmanaged project.

I need to know how can I take a string like this \"some data to encrypt\" and get a byte[] array which I\'m gonna use as the

相关标签:
7条回答
  • 2020-12-08 15:02

    Normally, encryption functions take

    encrypt(const void *ptr, size_t bufferSize);
    

    as arguments. You can pass c_str and length directly:

    encrypt(strng.c_str(), strng.length());
    

    This way, extra space is allocated or wasted.

    0 讨论(0)
  • 2020-12-08 15:07

    If you just need read-only access, then c_str() will do it:

    char const *c = myString.c_str();
    

    If you need read/write access, then you can copy the string into a vector. vectors manage dynamic memory for you. You don't have to mess with allocation/deallocation then:

    std::vector<char> bytes(myString.begin(), myString.end());
    bytes.push_back('\0');
    char *c = &bytes[0];
    
    0 讨论(0)
  • 2020-12-08 15:10

    From a std::string you can use the c_ptr() method if you want to get at the char_t buffer pointer.

    It looks like you just want copy the characters of the string into a new buffer. I would simply use the std::string::copy function:

    length = str.copy( buffer, str.size() );
    
    0 讨论(0)
  • 2020-12-08 15:10

    If this is just plain vanilla C, then:

    strcpy(buffer, text.c_str());
    

    Assuming that buffer is allocated and large enough to hold the contents of 'text', which is the assumption in your original code.

    If encrypt() takes a 'const char *' then you can use

    encrypt(text.c_str())
    

    and you do not need to copy the string.

    0 讨论(0)
  • 2020-12-08 15:12

    I dont think you want to use the c# code you have there. They provide System.Text.Encoding.ASCII(also UTF-*)

    string str = "some text;
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str);
    

    your problems stem from ignoring the encoding in c# not your c++ code

    0 讨论(0)
  • 2020-12-08 15:13

    std::string::data would seem to be sufficient and most efficient. If you want to have non-const memory to manipulate (strange for encryption) you can copy the data to a buffer using memcpy:

    unsigned char buffer[mystring.length()];
    memcpy(buffer, mystring.data(), mystring.length());
    

    STL fanboys would encourage you to use std::copy instead:

    std::copy(mystring.begin(), mystring.end(), buffer);
    

    but there really isn't much of an upside to this. If you need null termination use std::string::c_str() and the various string duplication techniques others have provided, but I'd generally avoid that and just query for the length. Particularly with cryptography you just know somebody is going to try to break it by shoving nulls in to it, and using std::string::data() discourages you from lazily making assumptions about the underlying bits in the string.

    0 讨论(0)
提交回复
热议问题