Skip to content
systemcoding.dev
Fundamentals

Decode a float Bit by Bit in C With memcpy

Copy a float into a uint32_t with memcpy, then mask out the sign, exponent and fraction fields to see exactly how IEEE 754 stores it.

6 min read
Summarize in AI
Flat illustration of a hex dump with one byte highlighted, with the C, Rust and Zig logos.

A float looks like a number in your source and behaves like one in arithmetic, but in memory it is 32 bits split into three fields. Once you can pull those fields apart yourself, a whole family of surprises (why 0.1f is not exactly one tenth, why the largest float has an exponent field of 254) stops being surprising. This post decodes a float in C17 with GCC 14 and glibc 2.40 on a little-endian x86-64 Linux machine, using nothing but memcpy, shifts and masks.

The layout comes from IEEE 754-2019, which defines the binary32 format that every mainstream C compiler maps to float. If you are new to the idea, the short version is that a float is scientific notation in base 2: a sign, an exponent and a fraction.

The three fields

A binary32 value is laid out from the most significant bit down:

BitsWidthNameMeaning
311sign0 positive, 1 negative
30 to 238exponent fieldthe exponent plus a bias of 127
22 to 023fraction fieldthe digits after the binary point

For a normal number the value is (-1)^sign * 1.fraction * 2^(exponent - 127). The leading 1 before the binary point is not stored. Hardware assumes it, which is why 23 stored bits give you 24 bits of precision. The two extreme exponent values are special: 0 means zero or a subnormal number, and 255 means infinity or NaN. Everything in between is an ordinary number.

Why memcpy and not a cast

The tempting way to get at the bits is a pointer cast:

c
uint32_t bits = *(uint32_t *)&f;   // wrong

That breaks the strict aliasing rule in C17 section 6.5 paragraph 7. An object with declared type float may only be accessed through an lvalue of a compatible type or a character type. Reading it through a uint32_t * is undefined behavior, and GCC at -O2 is allowed to assume the access cannot alias, which can reorder or delete it. It often appears to work at -O0 and then fails after an optimization flag changes.

There are two legal alternatives. A union with both members works in C (C17 footnote 95 says the bytes are reinterpreted), though it is not legal in C++. memcpy works in both languages, and it is the habit worth building. Copying sizeof f bytes into a uint32_t is defined, and GCC and Clang compile a fixed-size memcpy to a single register move, so you do not pay for it. Both compilers document this in their treatment of -fstrict-aliasing; the GCC manual describes the option and what it assumes.

We also need the two types to have the same size. On every platform GCC and Clang support, float is 32 bits, but a _Static_assert makes the assumption explicit and costs nothing.

Decoding one value

Take 0.15625f, which is 5/32. In binary that is 1.01 * 2^-3. The exponent field is -3 + 127 = 124, and the fraction .01 followed by zeros is 0x200000 once it fills the top of the 23-bit field. Putting the fields together gives 0 01111100 01000000000000000000000, which regroups into nibbles as 0011 1110 0010 0000 ... or 0x3E200000.

Here is the program that confirms it:

decode.cc
#include <stdint.h>
#include <stdio.h>
#include <string.h>

_Static_assert(sizeof(float) == sizeof(uint32_t), "float must be 32 bits");

int main(void) {
    float f = 0.15625f;
    uint32_t bits;
    memcpy(&bits, &f, sizeof bits);

    uint32_t sign = bits >> 31;
    uint32_t exponent = (bits >> 23) & 0xFFu;
    uint32_t fraction = bits & 0x7FFFFFu;

    printf("bits = 0x%08X\n", (unsigned)bits);
    printf("sign = %u\n", (unsigned)sign);
    printf("exponent field = %u (unbiased %d)\n",
           (unsigned)exponent, (int)exponent - 127);
    printf("fraction field = 0x%06X\n", (unsigned)fraction);
    return 0;
}

Compile with gcc -std=c17 -Wall -Wextra -o decode decode.c. The (unsigned) casts keep printf honest, because uint32_t is unsigned int on Linux but the standard does not promise that, and -Wformat complains when the types differ.

Text
bits = 0x3E200000
sign = 0
exponent field = 124 (unbiased -3)
fraction field = 0x200000

The shift-then-mask pattern is the whole trick. To isolate a field you shift it down to bit zero and mask off everything above its width: the sign needs no mask because shifting by 31 leaves one bit, the exponent needs 0xFF, and the fraction needs 0x7FFFFF (23 ones) with no shift.

Rebuilding the value from the fields

Decoding proves you can read the format. Rebuilding proves you understand it. To go the other way you pack the fields with shifts and |, then copy the bits back into a float:

rebuild.cc
#include <stdint.h>
#include <stdio.h>
#include <string.h>

static float make_float(uint32_t sign, uint32_t exponent, uint32_t fraction) {
    uint32_t bits = (sign << 31) | (exponent << 23) | fraction;
    float f;
    memcpy(&f, &bits, sizeof f);
    return f;
}

int main(void) {
    float a = make_float(0, 124, 0x200000);
    float b = make_float(1, 127, 0x400000);
    printf("%.5f\n", a);
    printf("%.1f\n", b);
    return 0;
}

The second call builds a negative number with exponent field 127 (unbiased 0) and fraction 0x400000, which is the bit .1 in binary, or one half. So the value is -1.5 * 2^0.

Text
0.15625
-1.5

Reading 0.1f

Now the payoff. Decode 0.1f the same way and you get bits = 0x3DCCCCCD, exponent field 123 and fraction 0x4CCCCD. The fraction is the repeating pattern 1100 1100 ... from the binary expansion of one tenth, rounded at the 23rd bit. That final D instead of C is the round-up, and it is the reason 0.1f is slightly larger than one tenth. Decimal fractions like this have no finite binary expansion, so the stored value is always the nearest representable neighbor. The exact stored value is 0.100000001490116119384765625, which you can confirm by printing %.27f.

Special values you will meet

Run the decoder on a few other inputs and the special encodings show up. Positive zero is all bits clear, 0x00000000, and negative zero differs only in the sign bit, 0x80000000. The two compare equal with == but print differently with printf("%f"), and 1.0f / -0.0f is negative infinity. Infinity has exponent field 255 and fraction 0, so +inf is 0x7F800000. A NaN has exponent field 255 and a nonzero fraction, and the top fraction bit separates a quiet NaN from a signaling one on most hardware. Checking isnan is the right test in real code, because the payload bits are not portable. When you debug a numerical bug, dumping the bits like this is often the fastest way to learn whether you are looking at a tiny value, a NaN that has been propagating for a while, or just an ordinary number that prints oddly.

Where this stops working

The decoder assumes float is IEEE binary32 and that uint32_t has the same endianness handling as the float on that machine. memcpy between the two types is safe on that assumption because it copies bytes in place, so byte order cancels out: you read the same 32-bit pattern you wrote. It would not cancel if you read the bytes through unsigned char * and assembled them by hand, or if you sent the bits over a wire. C also does not require IEEE 754: __STDC_IEC_559__ (or __STDC_IEC_60559_BFP__ in C23) is defined when the implementation conforms, and a freestanding target without it may use another format. For double the same method works with uint64_t, 11 exponent bits (bias 1023) and 52 fraction bits.

Share

Keep reading

Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Linux logos.
Systems Programming

How argc and argv Reach main in a C Program

The kernel copies argc and argv onto the new process's stack on execve, then startup code hands them to main. See the layout and measure it with a program.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.