This code demonstrates type punning, where the bitwise representation of...
September 2, 2025 at 12:24 PM
This code demonstrates type punning, where the bitwise representation of a float
is interpreted as a long
integer, then converted back to a float
.
Here’s how the code works step by step:
-
float y = .123f;
- A
float
variabley
is initialized with the value0.123
.
- A
-
long i = *(long *) &y;
- Here, the address of the
float
variabley
is cast to a pointer of typelong *
, and the value at that address is dereferenced and stored in thelong
variablei
. - This operation reinterprets the raw binary representation of
y
(as afloat
) as along
. It does not perform any conversion of the numerical value, but simply treats the binary bits as if they were along
.
- Here, the address of the
-
y = *(float *) &i;
- The address of the
long
variablei
is cast back to a pointer of typefloat *
, and the value at that address is dereferenced and assigned back to thefloat
variabley
. - This operation reinterprets the binary representation of
i
(as along
) as afloat
. Again, no numerical conversion happens here; the code simply reinterprets the bits.
- The address of the
Key Points:
- This is an example of type punning, which is generally undefined behavior in C and C++ due to strict aliasing rules, as the compiler assumes that objects of different types do not share memory. In practice, however, many compilers allow this behavior on common architectures.
- The binary representation of
0.123
as afloat
is preserved as it is cast between thefloat
andlong
types. At the end,y
will have the same original value (0.123
) if no corruption or unexpected behavior occurs due to the type punning.
Practical Use:
This type of code is often used in low-level programming for tasks like inspecting or manipulating the raw bitwise representation of a floating-point number, though more portable and safer approaches (e.g., using memcpy
) are preferred.
Generate your own explanations
Download our vscode extension
Read other generated explanations
Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node