Emertxe-News & Blog

Home » C » Pit-falls of Bit-fields
Pit-falls of Bit-fields

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 triedto 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 alwaysreturns size in bytes not in terms of bits. Use bit-wise operators instead, they are 100% safe and portable.

Best Embedded systems training institute with placements in Bangalore.

YOU MAY ALSO LIKE

Online Free IoT Internship for Engineering Students – 2023

Online Free IoT Internship for Engineering Students – 2023

The Internship Ecosystem An internship is a type of professional learning opportunity where engineering students get practical work related to their field of study or career interest. Through an internship, a student can explore and advance their career while...

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *