## 12.7 and narrowing signed integers

6.12 Expressions

Moderators: misra-c, david ward

tjotjos
Posts: 2
Joined: Mon Aug 30, 2010 10:17 pm
Company: Weastec

### 12.7 and narrowing signed integers

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: Select all

``````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: Select all

``````int_8 s8a;
uint_8 u8b;
...
u8b = ((uint_8)s8a & 0x7F;``````

tjotjos
Posts: 2
Joined: Mon Aug 30, 2010 10:17 pm
Company: Weastec

### Re: 12.7 and narrowing signed integers

edit: the second code sample should read

Code: Select all

``````int_8 s8a;
uint_8 u8b;
...
u8b = (uint_8)s8a & 0x7F;``````

misra-c
Posts: 572
Joined: Thu Jan 05, 2006 1:11 pm

### Re: 12.7 and narrowing signed integers

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