Reputation: 1262
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
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