Raphael Lopes
Raphael Lopes

Reputation: 153

Convert Char array to uint8_t vector

For some project i need to send encoded messages but i can only give vetor of uint8_t to be sent, and i have a char array (with numbers and string i converted to hexadecimal in it) and a pointer on the array. I encode the msg which is an object into the buffer then i have to send it and decode it etc.

char buffer[1024]
char *p = buffer
size_t bufferSize = sizeof(buffer)
Encode(msg,p,bufferSize)

std::vector<uint8_t> encodedmsg; //here i need to put my message in the buffer
Send(encodedmsg.data(),encodedmsg.size()) //Only taking uint8_t vector

Here is the prototype of send :

uint32_t Send(const uint8_t * buffer, const std::size_t bufferSize)                                                                         

I already looked at some questions but no one have to replace it in a vector or convert to uint8_t. I thinked bout memcpy or reinterpreted cast or maybe using a for loop but i don't really know how to do it whitout any loss.

Thanks,

Upvotes: 0

Views: 6064

Answers (1)

sklott
sklott

Reputation: 2859

Actually your code suggest that Send() function takes pointer to uint8_t, not std::vector<uint8_t>. And since char and uint8_t has same memory size you just could do:

Send(reinterpret_cast<uint8_t*>(p), bufferSize);

But if you want to do everything "right" you could do this:

encodedmsg.resize(bufferSize);
std::transform(p, p + bufferSize, encodedmsg.begin(), [](char v) {return static_cast<uint8_t>(v);});

Upvotes: 4

Related Questions