Magic of union


"union" is very useful C type which allows you to share the same memory block when using different types of variables. Although, the types of variable is different, but the content of the memory they share is the same. So by this way you can "read" the content by using shift and "&" operator if the content is formated and assigned by compiler.

Anyway, just remember "union" makes its members share the same memory block, and the size of memory block depends on the longest member.

The following is an example to show how to use "union" to transfer floating point to binary.

#include <stdio.h>

union ufloat /*here we share the unsigned integer and float variable in the same location*/
{
     float f;
     unsigned int i;
};
void print_float(float a)
{
     char bin[32]={0};
     char index=0;
     int tmp;
     ufloat u1;

     u1.f=a;
     tmp = u1.i; /*here we get the decimal conversion of float variable*/
    
     for(unsigned int j=1;j>0;j<<=1)
     bin[index++]=(tmp&j)?1:0; /*here we convert the decimal number into binary*/
     printf("output: %d ", bin[31]);
     for(char j=30;j>=0;j--)
     {
          printf("%d",bin[j]);
          if(j==27 || j==23 || j==19 || j==15
             || j==11 || j==7 || j==3)
          printf(" ");
     }
     printf("\n");
}
int main()
{
     float x=1.5;
     print_float(x);
     return 0;
}

Results:
output: 0 0111 1111 1000 0000 0000 0000 0000 000

Comments

Popular posts from this blog

Basic understanding of TLS-PSK protocol

Differences between ASIC, ASSP and ASIP

Orthogonal instruction set