c / expert
Snippet
IEEE 754 Floating-Point Bit Manipulation via Type-Punned Unions
Type-punning via C unions allows inspectable bit-level reinterpretation of floating-point representations without violating strict aliasing rules. Bitwise shift operations disassemble single-precision IEEE 754 numbers into sign, biased exponent, and mantissa fields.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdint.h>#include <stdbool.h>typedef union {float f;uint32_t u;} FloatBits;bool extract_ieee754_components(float val, uint8_t *sign, uint8_t *exponent, uint32_t *mantissa) {FloatBits fb = { .f = val };*sign = (fb.u >> 31) & 0x01;*exponent = (fb.u >> 23) & 0xFF;*mantissa = fb.u & 0x7FFFFF;return (*exponent != 0xFF);}
Breakdown
1
typedef union { float f; uint32_t u; } FloatBits;
Defines memory-overlapping union for valid C standard type-punning bit access.
2
FloatBits fb = { .f = val };
Initializes union with float value while providing binary representation alias through unsigned int member.
3
*sign = (fb.u >> 31) & 0x01;
Extracts sign bit by bit-shifting 31 positions to isolate most significant bit.