Get bytes from std::string in C++

后端 未结 7 1268
遇见更好的自我
遇见更好的自我 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: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.

提交回复
热议问题