Convert string to uint8_t array in C ++

I want a std :: string object (e.g. name) for a uint8_t array in C ++. The reinterpret_cast<const uint8_t*> function rejects my line. And since I'm encoding NS-3, some warnings are interpreted as errors.

+6
source share
2 answers

If you want a pointer to string data:

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

If you want to get a copy of string data:

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

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

 std::string name("sth"); const uint8_t* p = reinterpret_cast<const uint8_t*>(name.c_str()); 

Please note that this pointer will only be valid until the original string object is modified or destroyed.

+8
source

Source: https://habr.com/ru/post/898688/


All Articles