c / intermediate
Snippet
Unions for Type Punning
Unions allow the same memory location to be interpreted as different types. This 'type punning' is often used at an intermediate level to inspect the raw binary representation of data types like floats or doubles without using pointers or casts.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>typedef union {float f;unsigned int i;} FloatIntConverter;int main() {FloatIntConverter conv;conv.f = -1.0f;printf("Float: %f, Binary representation (hex): 0x%X\n", conv.f, conv.i);return 0;}
Breakdown
1
typedef union { ... } FloatIntConverter;
Defines a union where all members share the same starting memory address.
2
conv.f = -1.0f;
Stores a float value into the shared memory space.
3
conv.i
Accesses the same memory bits but treats them as an unsigned integer.