LearnFrenzy
Sign in Take a free test

Structures, Unions, Enums · Structure Programs · Question 6

See the IEEE 754 bits of a float with a union in C Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Print the raw 32-bit pattern of some float values, and split it into sign, exponent and mantissa.

Solution
main.c
#include <inttypes.h>
#include <stdio.h>

union bits {
    float f;
    uint32_t u;              /* same 4 bytes, read as an integer */
};

int main(void) {
    float values[] = {1.0f, -2.5f, 0.1f};
    for (int i = 0; i < 3; i++) {
        union bits b = {.f = values[i]};
        printf("%5.2f = 0x%08" PRIX32 "  sign %" PRIu32 ", exponent %3" PRIu32 ", mantissa 0x%06" PRIX32 "\n",
               values[i], b.u, b.u >> 31, (b.u >> 23) & 0xFF, b.u & 0x7FFFFF);
    }
    return 0;
}

Output Verified by compiling and running

 1.00 = 0x3F800000  sign 0, exponent 127, mantissa 0x000000
-2.50 = 0xC0200000  sign 1, exponent 128, mantissa 0x200000
 0.10 = 0x3DCCCCCD  sign 0, exponent 123, mantissa 0x4CCCCD

A float is 1 sign bit, 8 exponent bits (biased by 127) and 23 mantissa bits. 1.0 has exponent 127 (2⁰) and mantissa 0. 0.1 cannot be stored exactly – its mantissa is a repeating pattern, which is why 0.1 + 0.2 != 0.3. Reading another union member like this is allowed in C.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links