Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c - Bit fields portability

I read here that bit fields are not portable. Does that mean that the code below that defines bit fields (code taken from here) could not compile on certain machines?

If so, then why?

#include <stdio.h>
#include <string.h>

/* define simple structure */
struct
{
  unsigned int widthValidated;
  unsigned int heightValidated;
} status1;

/* define a structure with bit fields */
struct
{
  unsigned int widthValidated : 1;
  unsigned int heightValidated : 1;
} status2;

int main( )
{
   printf( "Memory size occupied by status1 : %d
", sizeof(status1));
   printf( "Memory size occupied by status2 : %d
", sizeof(status2));

   return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Bit fields are portable, in the sense that they are a part of the C language as specified in the standard (C11 section 6.7.2.1). Any compiler that fails to recognise code that uses bitfields is not standard-compliant. There's also nothing really questionable about your example, since all it does is have bitfields present.

What they probably mean is that the fields themselves may be packed unpredictably in location and order (allowed by the standard, previous ref. paragraph 11). This means that a struct with e.g. four bitfields of size 4, 12, 13 and 3 does not necessarily take up 32 bits and they won't necessarily be placed within the struct in that order; the compiler can place them where it likes. This means that the struct cannot be treated as an actual component-wise representation of an underlying binary object.

In contrast, bitmasks applied manually to integers exist exactly where you put them. If you define masks that mask out the first 4 bits, second 12 bits, etc. of an unsigned integer, the "fields" will actually apply to the bits, in order and in position (assuming you know the endianness, anyway). This makes the representation compiler-independent.

i.e. they are portable, but what they do may not necessarily be exactly what a person actually wanting to manipulate individual bits may need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...