I am looking for a way to efficiently and without UB convert a std::vector<uint8_t> to a std::vector<uint64_t> s.t each element in the std::vector<uint64_t> holds information from 8 elements from the std::vector<uint8_t>. The remainder elements should be filled with zeros but that can be done later.
The best approach I've come up with so far is:
std::vector<uint64_t> foo(std::vector<uint8_t> const & v8) {
std::vector<uint64_t> v64;
v64.reserve((v8.size() + 7) / 8);
size_t i = 0;
uint64_t tmp;
for(; i + 8 < v8.size(); i += 8) {
memcpy(&tmp, v8.data() + i, 8);
v64.push_back(tmp);
}
tmp = 0; // fill remainder with 0s.
memcpy(&tmp, v8.data() + i, v8.size() - i);
v64.push_back(tmp);
return v64;
}
But I'm hoping there is some cleaner / better approach.
Edit1: The solution about misses byte-order concerns. Pointed out by @VainMain.
Could be fixed with a byte-swap after the memcpy.