Mr S
Mr S

Reputation: 478

Convert vector of uint8 to string

I have a pointer to a vector of type uint8.

How would I take this pointer and convert the data in the vector into a full string representative of its content?

Upvotes: 22

Views: 39807

Answers (3)

deddebme
deddebme

Reputation: 465

For those who wants the conversion be done after a string is declared, you may use std::string::assign(), e.g.:

std::string str;
std::vector<uint8_t> v;
str.assign(v.begin(), v.end());

Upvotes: 11

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

You could just initialize the std::string with the sequence obtained from the std::vector<uint8_t>:

std::string str(v->begin(), v->end());

There is no need to play any tricks checking whether the std::vector<uint8_t> is empty: if it is, the range will be empty. However, you might want to check if the pointer is v is null. The above requires that it points to a valid object.

Upvotes: 45

user541686
user541686

Reputation: 210352

vector<uint8_t> *p;
string str(
    p && !p->empty() ? &*p->begin()             : NULL,
    p && !p->empty() ? &*p->begin() + p->size() : NULL);

Upvotes: 0

Related Questions