dvilela
dvilela

Reputation: 1262

How to cast, in C++, a byte vector (std::vector<uint8_t>) into different uint32_t, uint16_t and uint8_t variables

I have vector of bytes, std::vector, and I want to extract its information to some integers of different length.

For example I could have a vector of 7 bytes and I would like to read a uint32_t at the beginning, then a uint16_t and last a uint8_t. I need a way to specify at which element of the vector should it start reading and how many bytes should be read.

std::vector<std::uint8_t>& bytes(7);
uint32_t a;
uint16_t b;
uint8_t c;

// Could be something similar to this? 
// This yields an invalid conversion error: {aka unsigned char}’ to ‘const void*’
std::memcpy(&a, bytes[0], sizeof(uint32_t)); 
std::memcpy(&a, bytes[4], sizeof(uint16_t));
std::memcpy(&a, bytes[6], sizeof(uint8_t));

Upvotes: 0

Views: 8622

Answers (1)

Mestkon
Mestkon

Reputation: 4061

You can take the address of the element in the vector to achieve what you want:

std::memcpy(&a, &bytes[0], sizeof(std::uint32_t));
//              ^
//or use .data() instead
std::memcpy(&a, bytes.data() + 0, sizeof(std::uint32_t));    

Upvotes: 5

Related Questions