Copying data from POD vector to byte vector (pure)

Suppose I have a floating point vector that I want to "serialize" for lack of a better term to 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'm memcpy

floating to a variable uint32_t

, and the do-do offset and masking is inserting one byte at a time into myBytes

.

Since the memory is in these two contiguous, is there a way to do this more cleanly?

+3


source to share


2 answers


You can use unsigned char *

for aliases for other types without breaking strong alias, 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 are using a constructor that uses two iterators vector

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

      

+3


source


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;
}

      

+1


source







All Articles