Unions-Why And When To Use - Embedded C Programming Frequently Asked Interview Questions

When should unions be used? Why do we need them in Embedded Systems programming?

Unions are particularly useful in Embedded programming or in situations where direct access to the hardware/memory is needed. Here is a trivial example:

typedef union
{
struct  {
unsigned char byte1;
unsigned char byte2;
unsigned char byte3;
unsigned char byte4;
} bytes;
unsigned int dword;
} HW_Register;
HW_Register reg;

Then you can access the reg as follows:

reg.dword = 0×12345678;
reg.bytes.byte3 = 4;

Endianism and processor architecture are of course important.

Another useful feature is the bit modifier:

typedef union
{
struct  

{
unsigned char b1:1;
unsigned char b2:1;
unsigned char b3:1;
unsigned char b4:1;
unsigned char reserved:4;
}  

bits;
unsigned char byte;
}  

HW_RegisterB;
HW_RegisterB reg;

With this code you can access directly a single bit in the register/memory address:

x = reg.bits.b2;

Low level system programming is a reasonable example.

unions are used to breakdown hardware registers into the component bits. So, you can access an 8-bit register into the component bits.

This structure would allow a control register to be accessed as a control_byte or via the individual bits. It would be important to ensure the bits map on to the correct register bits for a given endianness.

typedef union  

{
unsigned char control_byte;
struct  

{
unsigned int nibble : 4;
unsigned int nmi : 1;
unsigned int enabled : 1;
unsigned int fired : 1;
unsigned int control : 1;
}
}  

ControlRegister;



More Embedded C Programming Questions-Answers:

Difference Between Process and Thread
What happens When Interrupt Occurs
Differences between Mutex And Semaphore
What is Storage class
Embedded C Basic Questions
C Programming Questions for Job Interview
Embedded C Programming Basic Questions for Job Interview
Data Declarations And qualifiers
Variables and Pointers Volatile Or Costant
Dangling and Wild Pointers

Related

Unions 4245243673828039727

Post a Comment

  1. Wonderfully written!! quite useful!!!

    ReplyDelete
  2. Thanks for sharing.. :)
    UK
    http://www.fashionablefoods.net

    ReplyDelete
  3. Thanks for your Expert comments.Keep Loving IngenuityDias.

    ReplyDelete

SPAMMING will not be Appreciated.

emo-but-icon

Hot in week

Recent

Comments

Our Channel

Contact Us

Name

Email *

Message *

Follow by Email

item