In the past few posts we have been checking various aspects related to bit fields. In
this blog, let we focus on how bit-lengths will pose a serious
issue to achieve portability in case of bit-fields structures.
Portability is basically about having the same program or application running across various processor architecture. When it comes to embedded systems portability plays a very important role as they have diversified set of hardware.
To start with, let us take a simple program as given below in Fig 1:
Fig
1: Bit-length pose and portability issue.
After
running the above code, output is shown in the given below Fig 2:
Note: source code is tested under gcc (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2 version.
Fig
2: Output of the source code given in Fig 1.
From
the above figure 2,
it is clear that when we declare the bit-length more than the
sizeof(int)[ In our case , it is 4 bytes] , which is compiler
dependent we are getting the error at the compile time. The above
code perfectly works fine , if the machine WORD size is 64 bits, but
fails to work with lower WORD size, which results in portability
issue.
Pointers
& Bit-fields
I
want to focus on one more problem, why pointers cannot be applied for
the bit-fields.let
me practically explain this problem by taking an example shown in the
fig 3 below,
Fig
3: Pointer operation and bit fields
The
output of the above source code is given below,
Fig
4: Output of the source code shown in fig 3.
One
can observe from the above fig 4, when tried
to reference the bit-field structure variable, compiler is generating
an error, this is because direct
addressing
of the bit-fields structure variables is not possible in C, since
the smallest unit of addressable memory in C is a sizeof(char)
i.e byte addressable not an bit addressable.
This
is one of the pit-fall of the bit-field structure in C programming.
From
the above two examples, we can conclude that how portability issue is
major concern with the bit-fields, and also we saw direct addressing
of the bit-fields is not possible in C programming. Apart from this
two issues, even sizeof() operator cannot also be applied for the
bit-fields since sizeof
always
returns size in bytes not in terms of bits. Use
bit-wise operators instead, they are 100% safe and portable.
No comments:
Post a Comment