Question about bit-fields and portability



Hello everyone,

I read here and there that bit-field usage should be avoided because
it's not portable. My question is why it's not portable?
For example let's say I have a struct in my code with bit-fields like
the following:

struct bitfield_t {
unsigned int val1 : 1;
unsigned int val2 : 3;
unsigned int val3 : 2;
};

How can such a bit-field struct be used in a non portable way? (Can
you give me an example if possible)

In my understanding non-portable means that if you save a struct like
this in a binary form (in a file for example or send it over the
network) and then try to restore it on a platform with different
endianness or compiler it probably will be interpreted differently. Is
this the only case in which the usage of bit-fields is not portable?

Will source code which contains bit-fields like bitfield_t work
(execute) the same on different platforms (Without considering how the
bits are saved on each platform)?

Thanks for your time
.



Relevant Pages

  • Re: Probable Bug in tcp.h
    ... An unportability in gcc's treatment of bit-fields results in gcc thinking ... an instance of the struct is not in fact aligned. ... Most modern C compilers support "unsigned char". ... Any more padding would be bogus. ...
    (freebsd-net)
  • Re: Pre-offsetof() question
    ... direct assignment of struct objects might ... Representations of types ... Except for bit-fields, objects are composed of contiguous sequences ... an identical structure definition did not result in identically laid ...
    (comp.lang.c)
  • Re: bit-fields and permitted types (and [OT] gcc)
    ... bit-field may only be a _Bool, signed int, unsigned int, or an implementation-defined type. ... why does the standard limit bit-fields to this list of types? ... is free to insert unnamed padding bytes after any struct element, so you cannot be 100% sure that your struct will have the size you require. ... a 32-bit register may react only if probed by a 32-bit instruction; trying to access two 16-bit halves might not work at all. ...
    (comp.lang.c)
  • Re: bit fields in a structure
    ... > UINT16 word; ... in the way it arranges bit-fields, ... Such use may be appropriate for a particular compiler ...
    (comp.lang.c)
  • Bit Fields
    ... I have the program illustrating use of Bit-Fields: ... int main ... struct DISK_REGISTER dr; ... I know that Bit-Fields are not-portable and probably the values generated are compiler/system specific. ...
    (comp.lang.c)