Share | Tweet |
---|
Learn C union declaration, initilization, array of unions, typedef, size of union, passing union or union pointer to function, function returning union or union pointer with examples, demonstrations.
To demonstrate abobe feature let's write a small program as shown below
#include "stdio.h"
struct S{
char c;
int i;
};
union U{
char c;
int i;
};
void main()
{
printf("sizeof struct S:%d,sizeof union U:%d\n", sizeof(struct S),sizeof(union U));
}
Program output:$ gcc prog,c $ ./a.out sizeof struct S:8,sizeof union U:4 $
Let's look at the below program to demonstrate this feature.
#include "stdio.h"
union U{
char c;
int i;
};
void main()
{
union U one;
printf("Char started at Address %x and integer started at Address %x\n",&one.c,&one.i);
one.i = 0x11223344;
printf("Add:%x,value:%x\nAdd:%x,value:%x\nAdd:%x,value:%x\nAdd:%x,value:%x\n",&one.c,one.c,(&one.c)+1,*((&one.c)+1),(&one.c)+2,*((&one.c)+2),(&one.c)+3,*((&one.c)+3));
if(one.c == 0x44){
printf("Little Endian\n");
}else{
printf("Big Endian\n");
}
}
Program output:$ gcc prog.c $ ./a.out Char started at Address 7ef7b20c and integer started at Address 7ef7b20c Add:7ef7b20c,value:44 Add:7ef7b20d,value:33 Add:7ef7b20e,value:22 Add:7ef7b20f,value:11 Little Endian $
Let's analyze the above program
We wrote hex number 0x11223344 into int i with 0x44 as LSB byte and 0x11 as MSB byte. Then, we have printed the address of char member c and its content. You will notice that char c content has changed along with the content of next bytes as well.
A machine is Little Endian if LSB byte is written at the lower address in memory and Big Endian if MSB byte is written at the lower memory location in memory. As we could check the content of character variable to know the endianness of the machine.
Let's write a small program to break up all bytes from an integer given by user.
#include "stdio.h"
union {
unsigned int n;
unsigned char c[4];
} data;
void main(){
int nRead = 0x11223344;
data.n = nRead;
for( int i = 0; i < 4; i++ )
{
printf( "Byte number %d of %ud in decimal %d in hex:%x\n", i, nRead, data.c[i], data.c[i] );
}
}
Program output:$ gcc prog.c $ ./a.out Byte number 0 of 287454020d in decimal 68 in hex:44 Byte number 1 of 287454020d in decimal 51 in hex:33 Byte number 2 of 287454020d in decimal 34 in hex:22 Byte number 3 of 287454020d in decimal 17 in hex:11 $
Share | Tweet |
---|
Search more C examples |
Search more C MCQs |
Linux Processes and Threads |
Git Version Control |
Linux IPC Mechanisms |
Linux OS Internals |
Linux OS Commands |
Series completion |
LCM and HCF of numbers |
Time and Distance |
SPI Protocol & Applications |
Microcontrollers, Tools & Peripherals |
UART Protocol & Applications |
I2C Protocol & Applications |