MISRA Discussion Forums
Underlying types for bit-fields - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C (https://forum.misra.org.uk/forumdisplay.php?fid=4)
+--- Forum: MISRA-C: 2004 rules (https://forum.misra.org.uk/forumdisplay.php?fid=17)
+---- Forum: 6.10 Arithmetic Type Conversions (https://forum.misra.org.uk/forumdisplay.php?fid=37)
+---- Thread: Underlying types for bit-fields (/showthread.php?tid=24)



Underlying types for bit-fields - gs - 21-02-2005

Can any one tell me how to determine the underlying type of a bit-field? We need to know in order to incorporate testing for MISRA 2 compliance in our product.


MISRA reply to question - MISRA Reply - 12-05-2005

The committee are considering this question further and will post a reply back in due course.


- MISRA Reply - 09-09-2005

The LRM says in 6.5.2.1

“ A bit-field shall have a type that is a qualifed or unqualified version of one of int, unsigned int, or signed int
… A bit field is interpreted as an integral type consisting of the specified number of bits”

The first section implies treat as an signed/unsigned int (bearing in mind MISRA rule 6.4). However the second line does open the door to allowing it to interpreted as a signed/unsigned char if the number of bits is small enough. Depending on which interpretation is chosen there are consequences on when casts are required. It is felt that this item needs to be discussed at the next MISRA working group in June.

Note: How do we assign values to a bit field. In all cases, we are doing an “implicit cast”.
Options
1) Round to nearest underlying type – 8, 16, 32.
2) It is a type dependent on the defined number of bits – 1..63. I.e. S/U1, S/U2,
3) Type on value – but how do you handle expressions?
4) Use the unsigned/signed int from the structure definition

Or wait for Strong Typing, which replaces these rules?

The underlying type of a bit-field is defined as follows
If the actual type of the bit-field is [un]signed, the underlying type is the smallest [un]signed type capable of accommodating the specified number of bits.

[The use of casting will not avoid the possibility of exceeding the range of a variable on assignment leading to truncation, this is also true of bit-field assignments.]

S.b2 = (U8) U16x;

S.b2 = U2fromU16(U16x);

Examples required.

S.b2 = U8a + U8b; /* Assume expression fits in U8, therefore will fit in U2 !! */