c / expert
Snippet
Strict-Aliasing Safe Type Punning via Byte-Wise Memory Copy
Direct pointer casting between incompatible types breaks the Strict Aliasing Rule, permitting invalid compiler optimization assumptions. Using memcpy reinterprets binary bit patterns safely across data types while optimizing out into register moves on modern compilers.
snippet.c
c
1
2
3
4
5
6
7
8
9
#include <stdio.h>#include <string.h>#include <stdint.h>uint32_t float_to_raw_bits(float val) {uint32_t bits;memcpy(&bits, &val, sizeof(val));return bits;}
Breakdown
1
uint32_t bits;
Allocates a target variable of identical byte size to store reinterpreted floating-point bits.
2
memcpy(&bits, &val, sizeof(val));
Performs a raw byte copy that avoids compiler undefined behavior caused by alias violations.
3
return bits;
Returns raw bitwise uint32_t representation without modifying the underlying IEEE-754 value.