16

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.

1
  • 3
    Show your code. What do you mean by "string object"? std::string or a pointer to a char. Commented Oct 5, 2011 at 16:27

3 Answers 3

36

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];
Sign up to request clarification or add additional context in comments.

13 Comments

reinterpret_cast<const uint8_t*>(myString.c_str()) would work though (assuming myString is a std::string).
+1: The std::vector is great stuff. Creates a simple copy without memcpy or other C style stuff that likes to pop up in answers to these kinds of questions.
@awoodland: While in C++03 it might not be null terminated, in C++11 the standard requires null termination of the buffer.
@Rob: I was told C++03 did not require it. However, I see it in C++11 at least. §21.4.1 / 5 ...for any basic_string object s, the identity &*(s.begin() + n) == &*s.begin() + n shall hold for all values of n such that 0 <= n < s.size().
David: I know it does that under the hood, it just hides the fragile and unnecessary details away so the code is a lot more readable and bugs for such operations become non-existant.
|
14

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.

1 Comment

Is there a way to do it backwards? For example, I would like to cast the uint8_t array to a c_str. Is that possible?
3

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.