Multiple choice

u32 X (f32 f) { union { f32 f; u32 n; } u; u.f = f; return u.n; }

Given the function X() is defined above, assume that u32 is a type-definition indicative of a 32-bit unsigned integer and that f32 is a type-definition indicative of a 32-bit floating-point number. Which of the following describes the purpose of the function defined above?

  1. X() effectively rounds f to the nearest integer value, which it returns.

  2. X() effectively performs a standard typecast and converts f to a roughly equivalent integer.

  3. X() preserves the bit-pattern of f, which it returns as an unsigned integer of equal size.

  4. Since u.n is never initialized, X() returns an undefined value. This function is therefore a primitive pseudo random number generator.

  5. Since u.n is automatically initialized to zero (0) by the compiler, X() is an obtuse way of always obtaining a zero (0) value.

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

The code defines a union containing a 32-bit floating-point number (f) and a 32-bit unsigned integer (n) sharing the same memory location. Assigning the float value to u.f and returning u.n reads the exact raw bit representation of the float as an integer without performing numerical type conversion.