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(‡). 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.
(‡) 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().
You have to binary shift your values for this to work:
myVector.at(0) = (myInt & 0xFF);
myVector.at(1) = (myInt >> 8) & 0xFF;
myVector.at(2) = (myInt >> 16) & 0xFF;
myVector.at(3) = (myInt >> 24) & 0xFF;
Your code is wrong:
int myInt = 0x12345678;
myVector.at(0) = myInt & 0x000000FF; // puts 0x78
myVector.at(1) = myInt & 0x0000FF00; // tries to put 0x5600 but puts 0x00
myVector.at(2) = myInt & 0x00FF0000; // tries to put 0x340000 but puts 0x00
myVector.at(3) = myInt & 0xFF000000; // tries to put 0x12000000 but puts 0x00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With