Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put a 4 Byte Integer into the first 4 char elements of vector

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;
like image 341
tzippy Avatar asked Jun 04 '13 08:06

tzippy


2 Answers

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 a vector<T, Allocator> where T is some type other than bool, then it obeys the identity

       &v[n] == &v[0] + n for all 0 <= n < v.size().
like image 169
jogojapan Avatar answered Nov 12 '22 14:11

jogojapan


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
like image 4
Gui13 Avatar answered Nov 12 '22 14:11

Gui13