On Sun, 13 Jul 2008 13:58:18 -0700 (PDT), DiAvOl <di****@freemail.gr>
wrote in comp.lang.c:
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?
There are several reasons why it is 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;
};
The first portability issue with this code is how large the structure
type will be. Even assuming 8-bit bytes (CHAR_BIT == 8), it may be a
single byte on some platforms, 2 or 4 bytes on others.
How can such a bit-field struct be used in a non portable way? (Can
you give me an example if possible)
One of the uses that bit-fields are put to is to map named bit fields
onto hardware devices.
On a platform with 8-bit memory access, this structure _might_ map
well onto the line control register of a memory-mapped 8250 UART, or
one if its enhanced descendents:
struct lcr
{
unsigned int word_size: 2;
unsigned int stop_bits: 1;
unsigned int parity_enable: 1;
unsigned int even_parity: 1;
unsigned int stick_parity: 1;
unsigned int break_ctrl: 1;
unsigned int div_latch_access: 1;
};
On another compiler for the same platform, this structure might
completely mis-match the logical bit fields with the hardware in the
device.
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?
There is actually a case from long ago where a certain vendor of PC
compilers changed the way bit-fields were laid out from one version of
their compiler to the next. Even though the operating system and
processor were the same.
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)?
If you generate and use bit-field structures with an application,
there are not much in the way of portability issues.
If you attempt to communicate them across any sort of communication
interface, or store them to a medium like a disk drive, flash memory,
etc., to be read back later, there can be problems. Not just on
different platforms but even on the same platform with different
compilers or even different versions of the same compiler.
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://c-faq.com/
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html