0 day streak
c / intermediate
Snippet

Unions for Type Punning

A union allows different members to share the exact same memory location. This is often used for 'type punning'—interpreting the same binary data as different types (e.g., viewing a float's bit pattern as an integer).

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
union DataOverlay {
float f;
unsigned int i;
};
int main() {
union DataOverlay data;
data.f = 1.0f;
printf("Float: %f, Bits as Int: 0x%X\n", data.f, data.i);
return 0;
}
Breakdown
1
union DataOverlay
Defines a union where all members share the same memory space.
2
data.f = 1.0f;
Sets the shared memory using the float representation.
3
data.i
Accesses the exact same bits but interprets them as an unsigned integer.