What can I do to avoid MISRA giving this error for the code below? I tried casting with (unit16_t). But then it didn\'t allow an explicit conversion.
Illegal implici
The MISRA rule is trying to ensure that the "underlying type" used for calculation is the same as the resulting type. To achieve that, you can cast the one, or both, of the operands:
uint8_t rate = 3U;
uint8_t percentage = 130U;
uint16_t basic_units = (uint16_t)rate * percentage;
On a 32-bit architecture the result without the cast is OK, however, consider the following:
uint32_t rate = ...;
uint32_t percentage = ...;
uint64_t basic_units = rate * percentage;
On a 32-bit architecture, the operation will be performed in 32 bits - even though the target type is 64 bits wide. Where rate and percentage are large enough, this could result in the operation wrapping in 32 bits and so data that would have fit in the target type will be lost.
The MISRA rule is attempting to make the code safer irrespective of the size of the types on the target platform.