When checking some code with Misra, it has generated following messages
Unpermitted operand to operator '>>' [MISRA 2012 Rule 10.1 required]
Unpermitted operand to operator '&' [MISRA 2012 Rule 10.1 required]
I wasn't able to understand the issue, and the description of Rule 10.1 is very general and does not help a lot. The relevant piece of code is bellow.
float variable2;
variable2= 814.00f;
Data[0] = (((Int16) variable2) >> 8) & ((Int16)0xFF);
Data[1] = ((Int16) variable2) & ((Int16)0xFF);
What is the issue with the use of operators in this code?
You shouldn't use signed integers in bitwise arithmetic, ever. There is a lot of poorly-defined behavior associated with it. Left-shifting a negative value gives undefined behavior. Right-shifting a negative value gives implementation-defined behavior (either arithmetic or logical shift).
Therefore MISRA-C has a requirement that all such variables should be of what they call essentially unsigned type.
In addition, using a 16 bit type no matter signedness isn't safe on a 32-bit system, because they will be implicitly promoted to 32-bit signed int
. I will assume that you are using a 32-bit system, or otherwise the use of floating point numbers likely makes little sense in the first place.
In your case, you can't go directly from float to unsigned, as you would lose the sign bit. Meaning you have to go one step to signed type first.
float f32 = 814.00f;
int32_t s32 = (int32_t)f32;
uint32_t u32 = (uint32_t)s32;
Data[0] = ((u32 >> 8) & 0xFFu);
Data[1] = (u32 & 0xFFu);
This should be MISRA-C compliant, though it depends on the type of Data
too.
u
suffix on integer constants is sufficient, you don't need to cast them.&
is required for advisory MISRA-C:2012 12.1. Your code was not compliant with this rule, the above code is.