Get bytes from std::string in C++


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 source for Encrypt.

In C# I do

  for (int i = 0; i < text.Length; i++)
    buffer[i] = (byte)text[i];

What I need to know is how to do the same but using unmanaged C++.


2/3/2009 5:53:48 AM

Accepted Answer

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());
char *c = &bytes[0];
4/26/2013 6:10:52 PM

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.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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow