Converting a string to uint8_t array in C++

Carlo picture Carlo · Oct 5, 2011 · Viewed 38.8k times · Source

I want an std::string object (such as a name) to a uint8_t array in C++. The function reinterpret_cast<const uint8_t*> rejects my string. And since I'm coding using NS-3, some warnings are being interpreted as errors.

Answer

Robᵩ picture Robᵩ · Oct 5, 2011

If you want a pointer to the string's data:

reinterpret_cast<const uint8_t*>(&myString[0])

If you want a copy of the string's data:

std::vector<uint8_t> myVector(myString.begin(), myString.end());
uint8_t *p = &myVector[0];