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.
问问题
46068 次
3 回答
30
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];
于 2011-10-05T16:26:57.733 回答
12
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.
于 2011-10-05T16:30:13.693 回答
1
If you need an actual array (not a pointer, as other answers have suggested; the difference is explained very nicely in this answer), you need to use std::copy
from <algorithm>
:
std::string str = "foo";
uint8_t arr[32];
std::copy(str.begin(), str.end(), std::begin(arr));
于 2021-01-10T19:48:00.757 回答