Reputation: 55
I would like to convert std::uint32
to std::vector<std::uint8>
in a better way than this:
std::uint32_t base_rva = 0xccddee00;
std::vector<std::uint8_t> vraw_data;
//copying base_rva to raw_data
vraw_data.resize(sizeof(base_rva));
std::memcpy(vraw_data.data(), &base_rva, sizeof(base_rva));
I was looking for something like:
std::vector<std::uint8_t> vraw_data((std::uint8_t*)&base_rva, sizeof(base_rva));
Any suggestions?
Upvotes: 2
Views: 7064
Reputation: 1
I was looking for something like:
std::vector<std::uint8_t> raw_data((std::uint8_t*)&base_rva, sizeof(base_rva));
There's no such constructor available for std::vector
, but supposed you want to store the copy of a std::uint32_t
internal representation in a std::vector<std::uint8_t>
you can simply do
std::uint32_t data = 42;
std::vector<std::uint8_t> raw_data( (std::uint8_t*)&data
, (std::uint8_t*)&(data) + sizeof(std::uint32_t));
according (4) from std::vector
constructors.
Upvotes: 5
Reputation: 1673
If you don't like casting, you could do it like...
union to_byte_vector
{
uint32_t val;
uint8_t bytes[1];
to_byte_vector() = default;
to_byte_vector(uint32_t v) : val(v) {}
to_byte_vector(const to_byte_vector& o) : val(o.val) {}
to_byte_vector& operator=(const to_byte_vector& o) { val = o.val; return *this; }
operator uint32_t() const { return val; }
std::vector<uint8_t> get_vector() const { return std::vector<uint8_t>(begin(), end()); }
private:
const uint8_t* begin() const { return bytes; }
const uint8_t* end() const { return bytes + sizeof(uint32_t); }
};
And use it like...
auto vec = to_byte_vector(42).get_vector();
But really, this is just letting the union
do the casting work for you.
Upvotes: 0