I have a function that takes an unsigned
value and transforms it into a std::vector<std::uint8_t>
. The requirements (and post conditions) are as follows:
- The code must utilize "modern C++" up to C++14
- The focus is on readability/maintainability first, performance second
- The most significant byte must be at index 0.
- The lease significant byte must be at index
size()-1
. - The return type cannot be changed; this is a requirement stemming from other code not shown in this context (larger application requirement). Also avoids a conversion from one container to
std::vector
. - The resulting vector must be as compact as possible. For values that decompose into fewer bytes than
sizeof(unsigned)
, the resulting vector must not contain unnecessary MSB's (that is, zero value bytes). - The code must be endianness-agnostic and portable to various other architectures and platforms.
Here is the current implementation I have:
using BinaryStreamByteVector = std::vector<std::uint8_t>;
BinaryStreamByteVector CreateMultiByteInteger(unsigned value)
{
BinaryStreamByteVector value_bytes;
while (value != 0)
{
std::uint8_t byte = value & 0xFF;
value_bytes.insert(value_bytes.begin(), byte);
value >>= 8;
}
return value_bytes;
}
I can't think of a better implementation for CreateMultiByteInteger
, so I'm hoping for other ideas that meet the requirements above.
const
array or aconst std:: array
(for retaining size information), which varies the size of the array returned using thesizeof
operator onunsigned
. That would be absolutely performant, I guess. The algorithm is perfect. You even include the masking of the higher-order bits. Unfortunately, you have a restriction on the return type, so this wouldn't help. However, maybe the idea of making it a template function will still help? \$\endgroup\$