在 C++ 中将字符串转换为 uint8_t 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7664529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a string to uint8_t array in C++
提问by Carlo
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.
我想要一个 std::string 对象(例如名称)到 C++ 中的 uint8_t 数组。该函数reinterpret_cast<const uint8_t*>
拒绝我的字符串。由于我使用 NS-3 进行编码,因此一些警告被解释为错误。
回答by Rob?
If you want a pointer to the string
's data:
如果你想要一个指向string
's 数据的指针:
reinterpret_cast<const uint8_t*>(&myString[0])
If you want a copy of the string
's data:
如果您想要string
's 数据的副本:
std::vector<uint8_t> myVector(myString.begin(), myString.end());
uint8_t *p = &myVector[0];
回答by sth
String objects have a .c_str()
member function that returns a const char*
. This pointer can be cast to a const uint8_t*
:
字符串对象有一个.c_str()
成员函数,它返回一个const char*
. 此指针可以转换为 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.
请注意,此指针仅在原始字符串对象未被修改或销毁时才有效。