Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
12.7 and narrowing signed integers
#1
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!
<t></t>
Reply
#2
edit: the second code sample should read
Code:
int_8 s8a;
uint_8 u8b;
...
u8b = (uint_8)s8a & 0x7F;
<t></t>
Reply
#3
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.
Posted by and on behalf of the MISRA C Working Group
Reply


Forum Jump:


Users browsing this thread: 3 Guest(s)