Next function works fine:
std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
return {(uint8_t*)&ui, (uint8_t*)(&ui+1)};
}
But its result depends on endianess of machine.
I also need to serialize bytes in reverse order:
std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
std::vector<uint8_t>::reverse_iterator
begin{(uint8_t*)(&ui+1)-1}
, end{(uint8_t*)(&ui)-1}; //ERROR: Calling a private constructor
return {begin, end};
}
I know multiple other ways to do serialization. The interest of this Q is to construct reverse_iterator from pointer in manner like first snippet does.
std::vector<uint8_t>::reverse_iterator
can only point to elements of a std::vector<uint8_t>
.
Use std::reverse_iterator<uint8_t *>
:
std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
using iter_t = std::reverse_iterator<std::uint8_t *>;
std::uint8_t *ptr = reinterpret_cast<std::uint8_t *>(&ui);
return {iter_t(ptr + sizeof ui), iter_t(ptr)};
}
You can use std::reverse
to help you with your task.
std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
std::vector<uint8_t> v{(uint8_t*)&ui, (uint8_t*)(&ui+1)};
std::reverse(v.begin(), v.end());
return v;
}
I took the above idea and rewrite it in own manner
std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
std::reverse_iterator<uint8_t*> begin{(uint8_t*)(&ui+1)}, end{(uint8_t*)(&ui)};
return {begin, end};
}
thank you @HolyBlackCat
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.