mercredi 12 février 2020

Evaluate the "real size" of a number

For "real size" I mean: does the number used actually fit inside the type of variable it should?

I have a variadic function (using parameter pack) that should receives only numeric values:

template<typename T1, typename... Tn>
std::vector<uint8_t> payloadFromValues(T1 first, Tn... others)

Each of these numeric arguments will be processed as int8_t, int16_t, int32_t, uint8_t, uint16_t, uint32_t or uint64_t. Then each one will be sliced byte by byte (least significant byte first) and finally returned as an 8 elements (uint8_t) vector (non-used elements are filled with zeros) that will finally be used as a payload to a CAN frame (CANopen protocol).

Example

An int argument for the function will be used as an uint8_t in the CAN frame.

The int type accepts values greater than 255, but uint8_t don't.

Inside the variadic function I'm evaluating the compliance between the numeric value input and the possibility (without loss of information) of use the input int as an uint8_t.

To do so, I'm using this logic:

//value: input argument for (usually "templated" as an unsigned int)
//size: the expected size (in bytes) from CAN point of view (can be 1, 2, 4 or 8)

if( (value >> (8 * size)) != 0)
{
    throw std::invalid_argument("Input value doesn't fit in expected size!\n");
}

Problem

I can't right shift (>>) an int 32 times..., in a case that an uint32_t is expected...

So, how could I tackle this problem?

Aucun commentaire:

Enregistrer un commentaire