Search code examples
cbit-manipulationmisra

Warning: "An expression which is the result of a ~ or << operation has not been cast to its essential type" - How to fix?


I' doing operation on bytes where I want to add an uint8 to the MSB of an existing uint32:

uint32 my_uint32;
my_uint32 = 0x00ffffffu;

my_uint32 = (uint32)(my_uint32) | ((uint8)(0x2u) << 24u));  // Add value 0x02 to the MSB of my_uint32 
my_uint32 = 0x02ffffffu    // This is what I get and is working so far

This is so far OK but I get the warning:

"An expression which is the result of a ~ or << operation has not been cast to its essential type"

I can get ride of the warning by doing:

my_uint32 = ((uint32)(my_uint32) | (uint8)((0x2u) << 24u)); // Here I'm doing the uint8 cast on the complete shift operation

But than this will not work. The result would be:

my_uint32 = 0x00ffffffu

Anyone idea how I can get away from the warning?


Solution

  • Change my_uint32 = (uint32)(my_uint32) | ((uint8)(0x2u) << 24u)); to my_uint32 = my_uint32 | ((uint32) 0x2u << 24);.

    Essentially, the left operand of a shift should be converted to the desired result type, so that the shift is performed with that type. Casting it to uint8 results in the shift being done with an int type, due to automatic promotion.