Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string to uint8_t array in C++

Tags:

c++

ns-3

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.

like image 444
Carlo Avatar asked Oct 05 '11 16:10

Carlo


1 Answers

String objects have a .c_str() member function that returns a const char*. This pointer can be cast to a const uint8_t*:

std::string name("sth");

const uint8_t* p = reinterpret_cast<const uint8_t*>(name.c_str());

Note that this pointer will only be valid as long as the original string object isn't modified or destroyed.

like image 104
sth Avatar answered Sep 28 '22 10:09

sth