I want to know how to convert any byte sequence to an unsigned integral type, the byte sequence in question can have any length from 1 to 8 (inclusive), and the types are uint8_t
, uint16_t
, uint32_t
and uint64_t
.
The conversion is simple, treat the byte sequence as binary representation of an unsigned integer, it can contain padding bytes, and it can be encoded in either little endian or big endian, the task is to write two functions that parses the byte sequence into an unsigned integer type with the least width, one for each endianness.
Ignoring padding bytes, if the byte sequence after parsing is between 0 and 255, it should be cast to uint8_t
, else if it is between 256 and 65535, it should be cast to uint16_t
. 65536 – 4294967295 -> uint32_t
, 4294967296 – 18446744073709551615 -> uint64_t
. If uint64_t
can’t hold the number, an exception needs to be thrown.
It is trivial for me to write parsers for each type and endianness combination, it is extremely easy, but I would have to write 8 overload functions and it doesn’t solve the problem of all those wasted padding bytes.
Below is my attempt at doing this for little endian, it doesn’t compile:
#include <vector>
using std::vector;
typedef vector<uint8_t> bytes;
using Unsigned_Int = std::tuple<
std::uint8_t,
std::uint16_t,
std::uint32_t,
std::uint32_t,
std::uint64_t,
std::uint64_t,
std::uint64_t,
std::uint64_t
>;
auto parse_LittleEndian(const bytes& arr) {
size_t size = arr.size();
if (size > 8) {
throw;
}
uint64_t number, width, shift, byte, place;
number = width = shift = 0;
for (size_t i = 0; i < size; i++) {
byte = arr[i];
number |= byte << shift;
shift += 8;
place = bool(byte) * i;
width = (width > place) * width + (place >= width) * place;
}
using UInt = std::tuple_element<width, Unsigned_Int>;
return UInt(number);
}
The error is caused by width
, it says expression must have a constant value, the value of variable "width" (declared at line 120) cannot be used as a constant
.
I have no idea how to fix it. And I don’t think my method to be very efficient.
What is a more efficient way to achieve this?