MISRA Discussion Forums

Full Version: 12.7 and narrowing signed integers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a question concerning Rule 12.7: Bitwise operators shall not be applied to operands whose underlying type is signed.

I need to transmit a 7-bit signed integer (values are restricted -64 - +63). My current method, shown below, seems to be inconsistent with 12.7.
Code:
int_8 s8a;
uint_8 u8b;
...
u8b = s8a & 0x7F;

Is the following an acceptable solution, or a violation of 10.1? Do I need to use a deviation here for the 7-bit integer?
Code:
int_8 s8a;
uint_8 u8b;
...
u8b = ((uint_8)s8a & 0x7F;

Thank you for your help!
edit: the second code sample should read
Code:
int_8 s8a;
uint_8 u8b;
...
u8b = (uint_8)s8a & 0x7F;
The underlying type of (uint_8)s8a is uint_8.

The type of the constant 0x7F is int. The underlying type of 0x7F is therefore the smallest signed integer type that can hold it. This will be implementation-defined, but on many implementations it will be signed char.

There must therefore be an implicit conversion between signed and unsigned underlying types and this conversion violates rule 10.1.

To avoid this, you could write (uint_8)s8a & 0x7Fu because the 'u' suffixes forces 0x7F to take an unsigned type.