I have a vector<unsigned char>
and want to put a 4 byte Integer
into the first 4 elements.
Is there a simpler way in C++ than masking like this:
myVector.at(0) = myInt & 0x000000FF;
myVector.at(1) = myInt & 0x0000FF00;
myVector.at(2) = myInt & 0x00FF0000;
myVector.at(3) = myInt & 0xFF000000;
A std::vector
is guaranteed to be stored as one contiguous block of data(&ddagger). Hence it is possible to treat a std::vector<unsigned char>
in basically the same way as an unsigned char
buffer. This means, you can memcpy
your data into the vector, provided you are sure it is large enough:
#include <vector>
#include <cstring>
#include <cstdint>
int main()
{
std::int32_t k = 1294323;
std::vector<unsigned char> charvec;
if (charvec.size() < sizeof(k))
charvec.resize(sizeof(k));
std::memcpy(charvec.data(), &k, sizeof(k));
return 0;
}
Note: The data()
function of std::vector
returns a void*
to the internal buffer of the vector. It is available in C++11 – in earlier versions it is possible to use the address of the first element of the vector, &charvec[0]
, instead.
Of course this is a very unusual way of using a std::vector
, and (due to the necessary resize()
) slightly dangerous. I trust you have good reasons for wanting to do it.
(&ddagger) Or, as the Standard puts it:
(§23.3.6.1/1) [...] The elements of a vector are stored contiguously, meaning that if
v
is avector<T, Allocator>
whereT
is some type other thanbool
, then it obeys the identity&v[n] == &v[0] + n for all 0 <= n < v.size().