A C language union is a shared data space accessed via different data types. This feature can be handy, providing that you tag the union data as was seen in this Lesson. But I’m after exploiting a union for a more abusive yet useful purpose.
My goal is to exploit a union’s weakness by accessing a specific data type through another data type to reveal out real numbers are stored in binary. The union provides a tool I can use to “peek under the hood” and see the binary format directly. But first, consider the following example:
2026_10_17-Lesson.c
#include <stdio.h>
int main()
{
union real {
float a;
long b;
char c[8];
};
union real numb;
int x;
numb.a = 10.0;
printf("The value of numb.a is %f\n",numb.a);
printf("The value of numb.b is 0x%0lX\n",numb.b);
printf("Union numb occupies %lu bytes:",sizeof(numb));
for( x=0; x<8; x++ )
printf(" %02X",numb.c[x]);
putchar('\n');
return 0;
}
In the code, union real contains three data types all sharing the same storage: a float, a long, and a four-char array.
The program assigns the value 10.0 to float variable numb.a. This same value is output as a long stores it (in numb.b) and then the individual bytes are output as stored in the char array numb.c[]:
The value of numb.a is 10.000000 The value of numb.b is 0x41200000 Union numb occupies 8 bytes: 00 00 20 41 00 00 00 00
Variable numb.a is assigned real number 10.0. When read as a long int, the value is 0x41200000. This value reflects the way real numbers are stored in binary, so it’s not the same as 0x0A or 10 decimal.
The output for char array numb.c[] is interesting to me. It shows how the bytes appear in memory for the real number 10.0. But the values are output backwards as a long int, which reflects the way CPUs store data.
It’s all fascinating stuff, but what intrigues me the most is how binary data represents a real number. The value 10 is stored as 0x41200000. So what’s going on with those bits that cause them to be interpreted as 10.0? And what about the precision or accuracy of the value? How is that accounted for?
In next week’s Lesson I cover the mystery of how real numbers are stored in binary.