Phonon
Phonon

Reputation: 12737

Copy data from POD vector to vector of bytes (cleanly)

Suppose I have a vector of floats that I want to "serialize", for the lack of a better term, into a vector of bytes, i.e.

std::vector<float> myFloats = {1.0, 2.0, 3.0, 4.0};
std::vector<unsigned char> myBytes;

Right now, I memcpy float to a uint32_t variable, and the do bit shifting and masking to insert one byte at a time into myBytes.

Since memory in these two is contiguous, is there a way for me to do it more cleanly?

Upvotes: 3

Views: 452

Answers (2)

AngelCastillo
AngelCastillo

Reputation: 2435

You can do something like this:

std::vector<unsigned char>
getByteVector(const std::vector<float>& floats)
{
  std::vector<unsigned char> bytes(floats.size() * sizeof(float));
  std::memcpy(&bytes[0], &floats[0], bytes.size());

  return bytes;
}

Upvotes: 1

Praetorian
Praetorian

Reputation: 109219

You're allowed to use unsigned char * to alias into other types without violating strict aliasing, so the following will work

std::vector<float> myFloats = {1.0, 2.0, 3.0, 4.0};
std::vector<unsigned char> myBytes{reinterpret_cast<unsigned char *>(myFloats.data()),
                                   reinterpret_cast<unsigned char *>(myFloats.data() + myFloats.size())};

You're making use of the vector constructor that takes two iterators

template< class InputIt >
vector( InputIt first, InputIt last,
        const Allocator& alloc = Allocator() );

Upvotes: 3

Related Questions