On this page

double stores an approximation, x87 computes in 80 bits, and SSE2 holds numbers in flat xmm registers—and every single one of those facts changes your result.

In C99, 0.1 + 0.2 does not equal 0.3, and printf("%.17g", ...) prints two different numbers. That isn’t a compiler bug or “sloppy hardware precision”—it’s a direct consequence of the binary storage format. In this lesson, I break down the IEEE 754 standard, the eight-slot x87 stack, and the flat SSE2 registers.

Mental Model: Three Fields and Two Access Models

What it looks like in C99 What happens in hardware
double is just a number The value is split into sign, exponent, and mantissa
0.1 is stored exactly 0.1 is an infinite repeating fraction in binary and gets rounded
x87 is an ordinary register file Eight slots with a TOP pointer; fld decrements the top pointer
SSE2 also works like a stack xmm registers are flat: addsd names two registers and writes the result directly
NaN equals itself QNaN compares unequal to everything, including itself

IEEE 754: Sign, Exponent, and Mantissa

A double occupies 64 bits divided into three fields: 1 sign bit, 11 biased-exponent bits, and 52 fractional mantissa bits.

Field double float
Sign 1 bit 1 bit
Exponent 11 bits 8 bits
Fractional mantissa 52 bits 23 bits

The numeric value is reconstructed as:

x=(−1)s×1.m×2e−b x = (-1)^s \times 1.m \times 2^{e-b}
where
ss
sign bit: 0 for positive, 1 for negative.
mm
fractional part of the mantissa; the leading 1 before the binary point is implicit.
ee
biased exponent from the exponent field.
bb
bias: 1023 for double, 127 for float.

The leading 1 before the binary point isn’t stored because every normalized binary number starts with 1—giving one extra bit of precision for free. The two exceptions are the extreme exponent values: e = 0 (zero and subnormal numbers without the implicit leading one) and all-ones e (Inf and NaN, such as 0x7ff8000000000000).

The fractional field m encodes the sum b1⋅2−1+b2⋅2−2+…b_1 \cdot 2^{-1} + b_2 \cdot 2^{-2} + \dots, so 0.6100.6_{10} becomes the repeating binary fraction 0.1001‾2=0x9999...0.\overline{1001}_2 = \mathtt{0x9999...}, and 0.1100.1_{10} equals 1.6⋅2−41.6 \cdot 2^{-4}. The diagram below shows the field boundaries and bit widths:

double 0.1 = 0x3fb999999999999a
  fields: s = 1 bit | e = 11 bits (0x3fb) | m = 52 bits (0x999999999999a ≈ 0.6)
  bits:   0         | 0111 1111 011       | 1001 1001 1001 ... 1010

float 0.1 = 0x3dcccccd
  fields: s = 1 bit | e = 8 bits (0x7b)   | m = 23 bits (0x4ccccd ≈ 0.6)
  bits:   0         | 0111 1011           | 100 1100 1100 1100 1100 1101

The 9-bit s+e header splits the third hex digit 'c' of 0x3dcccccd across
the exponent (1 bit) and the mantissa (3 bits).

The float_sse.c testbed prints the raw bits of both 0.1 representations:

  • double 0.1: 0x3fb999999999999a — sign 0, exponent 0x3fb (1019 - 1023 = -4), fractional mantissa 0x999999999999a (≈0.6\approx 0.6); with the implicit leading 1, the significand is 1.61.6.
  • float 0.1: 0x3dcccccd — sign 0, exponent 0x7b (123 - 127 = -4), fractional mantissa 0x4ccccd (≈0.6\approx 0.6, significand 1.61.6); hex digits shift by one bit because of the 9-bit header.

Both store the same mathematical number 1.6⋅2−41.6 \cdot 2^{-4}, just with different mantissa widths. In binary, 0.1 is the infinite repeating fraction 0.0001100110011..., so the register holds the nearest representable value, not the exact decimal.

Adding two rounded values produces a third rounded value:

  • 0.1 + 0.2 = 0.30000000000000004 (0x3fd3333333333334) — the sum of two already-rounded approximations.
  • 0.3 = 0.29999999999999999 (0x3fd3333333333333) — an independent approximation rounded on its own.
  • equal: false — the bit patterns differ by one least-significant bit, so == returns false.

The x87 Stack: Eight Slots and a Ninth fld

x87 computes in an 80-bit extended format: 1 sign bit, 15 exponent bits, and 64 mantissa bits. There are eight physical registers, and TOP tracks the current top st0. fld decrements TOP and pushes a value; fstp reads the top and increments TOP.

On x86-64, GCC and Clang always emit flat SSE2 instructions on xmm registers for float and double, leaving the 80-bit x87 stack mainly for long double and legacy code.

x87_overflow.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; x87_overflow.asm — eight x87 slots and a ninth fld.

default rel

%define SYS_EXIT 60
%define EXIT_OK 42

section .rodata
    values: dd 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0

section .text
    global _start

; ------------------------------------------------------------------------------
; _start — loads eight values, then issues a ninth fld on a full stack.
; Input:     none
; Output:    does not return; exits with 42 when x87 exceptions are masked
; Clobbers:  rax, rbx, rcx, rdi, r11, x87 stack, flags
; ------------------------------------------------------------------------------
_start:
    lea rbx, [values]
    mov ecx, 8

.loop:
    fld dword [rbx]
    add rbx, 4
    dec ecx
    jnz .loop

after_fld8:
    fld dword [rbx]

after_fld9:
    ; syscall: exit(EXIT_OK)
    mov edi, EXIT_OK
    mov eax, SYS_EXIT
    syscall

section .note.GNU-stack noalloc noexec nowrite progbits

objdump shows the exact machine instructions:

0000000000401000 <_start>:
  401000:	48 8d 1d f9 0f 00 00 	lea    rbx,[rip+0xff9]        # 402000 <values>
  401007:	b9 08 00 00 00       	mov    ecx,0x8

000000000040100c <_start.loop>:
  40100c:	d9 03                	fld    DWORD PTR [rbx]
  40100e:	48 83 c3 04          	add    rbx,0x4
  401012:	ff c9                	dec    ecx
  401014:	75 f6                	jne    40100c <_start.loop>

0000000000401016 <after_fld8>:
  401016:	d9 03                	fld    DWORD PTR [rbx]

0000000000401018 <after_fld9>:
  401018:	bf 2a 00 00 00       	mov    edi,0x2a
  40101d:	b8 3c 00 00 00       	mov    eax,0x3c
  401022:	0f 05                	syscall
  • lea rbx, [values] loads the array address; default rel makes it RIP-relative.
  • fld dword [rbx] loads a 32-bit float and widens it to 80 bits on the top of the stack.
  • add rbx, 4 advances the pointer to the next element.
  • dec ecx and jne repeat the load exactly eight times.
  • after_fld8 pauses right before the ninth fld; that ninth fld immediately follows.
  • mov edi, 0x2a returns exit status 42 provided the exception is masked.

In GDB at after_fld8, the stack is completely full:

(gdb) break after_fld8
Breakpoint 1 at 0x401016: file x87_overflow.asm, line 33.
(gdb) run
Starting program: .../lessons/16-float-x87-sse2/build/x87_overflow

Breakpoint 1, after_fld8 () at x87_overflow.asm:33
33	    fld dword [rbx]
(gdb) info float
  R7: Valid   0x3fff8000000000000000 +1
  R6: Valid   0x40008000000000000000 +2
  R5: Valid   0x4000c000000000000000 +3
  R4: Valid   0x40018000000000000000 +4
  R3: Valid   0x4001a000000000000000 +5
  R2: Valid   0x4001c000000000000000 +6
  R1: Valid   0x4001e000000000000000 +7
=>R0: Valid   0x40028000000000000000 +8

Status Word:         0x0000
                       TOP: 0
Control Word:        0x037f   IM DM ZM OM UM PM
                       PC: Extended Precision (64-bits)
                       RC: Round to nearest
Tag Word:            0x0000
Instruction Pointer: 0x00:0x00000000
Operand Pointer:     0x00:0x00000000
Opcode:              0x0000

A single nexti executes the ninth fld, changing the state:

(gdb) nexti
after_fld9 () at x87_overflow.asm:37
37	    mov edi, EXIT_OK
(gdb) info float
=>R7: Special 0xffffc000000000000000 Real Indefinite (QNaN)
  R6: Valid   0x40008000000000000000 +2
  R5: Valid   0x4000c000000000000000 +3
  R4: Valid   0x40018000000000000000 +4
  R3: Valid   0x4001a000000000000000 +5
  R2: Valid   0x4001c000000000000000 +6
  R1: Valid   0x4001e000000000000000 +7
  R0: Valid   0x40028000000000000000 +8

Status Word:         0x3a41   IE                       SF      C1
                       TOP: 7
Control Word:        0x037f   IM DM ZM OM UM PM
                       PC: Extended Precision (64-bits)
                       RC: Round to nearest
Tag Word:            0x8000
Instruction Pointer: 0x00:0x00000000
Operand Pointer:     0x00:0x00000000
Opcode:              0x0000
  • TOP: 0 means st0 is physical slot R0 holding +8; the remaining slots run from R7 through R1.
  • After the ninth fld, TOP wraps to 7, and R7 turns Special with Real Indefinite (QNaN): 9.0 never appears in any slot.
x87 ring: every fld decrements TOP by 1 (mod 8)
  Start (empty):        TOP=0
  fld #1..#8 (+1..+8):  R7(+1) -> R6(+2) -> ... -> R0(+8), TOP=0 (stack full)
  fld #9 (+9):          TOP=7 lands on occupied R7 (Tag=Valid)
                        ──► Stack Fault (IE, SF, C1) ──► R7 = QNaN

Status Word and Control Word list the flags and masks. Control Word is the control word; the abbreviations in both lines mean:

Flag Meaning Meaning here
IE Invalid Operation invalid operation raised
SF Stack Fault x87 stack overflow or underflow raised
C1 condition / stack overflow flag 1 — stack overflowed
IM–PM exception masks: Invalid, Denormal, Zero-divide, Overflow, Underflow, Precision all six are 1, so no trap/signal is raised
PC Precision Control Extended Precision (64-bits) — 64-bit mantissa
RC Rounding Control Round to nearest — round to nearest, ties to even
  • Status Word 0x3a41 sets IE, SF, and C1; C1 = 1 signals stack overflow.
  • Control Word 0x037f masks all six exceptions, so instead of raising a signal the CPU writes QNaN at the top and keeps running.
  • PC: Extended Precision (64-bits) selects 64-bit mantissa precision; RC: Round to nearest selects round-to-nearest-even.

QNaN is the quiet “not a number” marker that x87 writes on a masked stack overflow.

SSE2: Flat xmm Registers and a Single addsd

SSE2 has no top-of-stack pointer. Each xmm register is a flat 128-bit register addressed directly by number. The scalar addsd instruction adds the low 64 bits of two registers and leaves the sum in the destination.

float_sse.c
/* SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 */

/* float_sse.c — C99 testbed: binary fractions, comparisons, and quiet NaN. */

#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

static uint64_t double_bits(double value)
{
    uint64_t bits = 0;

    memcpy(&bits, &value, sizeof(bits));

    return bits;
}

static uint32_t float_bits(float value)
{
    uint32_t bits = 0;

    memcpy(&bits, &value, sizeof(bits));

    return bits;
}

double test_add(double a, double b)
{
    return a + b;
}

int test_equal(double a, double b)
{
    return a == b;
}

int main(void)
{
    volatile double a = 0.1;
    volatile double b = 0.2;
    volatile double c = 0.3;
    double sum = test_add(a, b);
    uint64_t qnan_bits = UINT64_C(0x7ff8000000000000);
    double qnan = 0.0;

    memcpy(&qnan, &qnan_bits, sizeof(qnan));

    printf("0.1 + 0.2 = %.17g\n", sum);
    printf("0.3       = %.17g\n", c);
    printf("equal: %s\n", test_equal(sum, c) ? "true" : "false");
    printf("double 0.1: 0x%016" PRIx64 "\n", double_bits(0.1));
    printf("float  0.1: 0x%08" PRIx32 "\n", float_bits(0.1f));
    printf("qnan: 0x%016" PRIx64 ", qnan == qnan: %s\n", double_bits(qnan),
           qnan == qnan ? "true" : "false");

    return 0;
}

Running the testbed prints the exact bit patterns and comparison outcomes:

0.1 + 0.2 = 0.30000000000000004
0.3       = 0.29999999999999999
equal: false
double 0.1: 0x3fb999999999999a
float  0.1: 0x3dcccccd
qnan: 0x7ff8000000000000, qnan == qnan: false

Compiling with -O2 -S -masm=intel reduces both functions to two short sequences:

test_add:
	addsd	xmm0, xmm1
	ret

test_equal:
	xor	eax, eax
	ucomisd	xmm0, xmm1
	mov	edx, 0
	setnp	al
	cmovne	eax, edx
	ret
  • addsd xmm0, xmm1 adds the low double lanes of xmm0 and xmm1, returning the sum in xmm0.
  • ucomisd xmm0, xmm1 compares two doubles and sets ZF, PF, and CF.
  • xor eax, eax zeros all of eax beforehand (before ucomisd), because setnp al writes only the low byte without clearing upper bits, and running xor later would clobber the flags.
  • mov edx, 0 sits after ucomisd safely because mov does not touch RFLAGS.
  • setnp al rejects the PF = 1 unordered case so comparing against QNaN never evaluates to equal.
  • cmovne eax, edx moves 0 from edx into eax when ZF = 0 (ordinary inequality), leaving 1 in eax only when both ZF = 1 and PF = 0—true equality without NaN.
Case ucomisd flags setnp al cmovne eax, edx Final eax
a == b ZF=1, PF=0, CF=0 al = 1 not taken 1
a != b ZF=0, PF=0, CF=0/1 al = 1 copies 0 from edx 0
NaN ZF=1, PF=1, CF=1 al = 0 not taken 0

In GDB, you can inspect a 128-bit xmm register as two double lanes:

Breakpoint 1, test_add (a=0.10000000000000001, b=0.20000000000000001)
    at float_sse.c:30
30	    return a + b;
(gdb) print $xmm0.v2_double
$1 = {0.10000000000000001, 0}
(gdb) print $xmm1.v2_double
$2 = {0.20000000000000001, 0}
(gdb) nexti 3
(gdb) print $xmm0.v2_double
$3 = {0.30000000000000004, 0}
  • v2_double views a 128-bit xmm register as two doubles; the second lane stays 0 because scalar instructions only touch the low 64 bits.
  • On entry xmm0 holds a and xmm1 holds b; after addsd, xmm0 holds 0.30000000000000004.
  • 0x7ff8000000000000 in qnan has sign 0, all 11 exponent bits set to 1, and the top mantissa bit set to 1; that’s why QNaN isn’t equal even to itself.

The suffix after the dot in the register name tells GDB how to slice the 128 bits of an xmm register:

View Layout Prints
.v2_double 2 × 64-bit two doubles
.v4_float 4 × 32-bit four floats
.v2_int64 2 × 64-bit two int64_ts
.v4_int32 4 × 32-bit four int32_ts
.v8_int16 8 × 16-bit eight int16_ts
.v16_int8 16 × 8-bit sixteen int8_ts

v2_double above is just one view; the integer and float views come in handy when inspecting packed SIMD registers.

AVX extends this same flat model to wider registers while x87 remains a separate legacy stack. More on that in lesson 21.

Common Pitfalls

  1. "0.1 + 0.2 should equal 0.3."
    Fact: the testbed prints 0.30000000000000004 and 0.29999999999999999, and == returns false.
    Cause: 0.1, 0.2, and 0.3 have no finite binary representation; each rounds independently.
    Fix: compare with a tolerance (fabs(a - b) < eps), or represent money and exact quantities in integer units.

  2. “A ninth fld simply evicts the oldest value.”
    Fact: after the ninth fld, TOP = 7, R7 holds Real Indefinite (QNaN), and R0 still holds +8; 9.0 is nowhere on the stack.
    Cause: pushing onto a full x87 stack raises a stack fault and, when masked, writes QNaN to the top instead of rotating the ring.
    Fix: keep x87 stack depth at most eight and spill intermediates to memory with fstp.

  3. "float and double store the exact same value."
    Fact: 0.1 encodes as 0x3fb999999999999a in double and 0x3dcccccd in float.
    Cause: float has only 23 mantissa bits vs. 52 in double, producing a coarser rounding.
    Fix: default to double for computation and reserve float for memory-bound arrays or wire formats.

  4. “Checking je after ucomisd is enough to test equality.”
    Fact: qnan == qnan returns false, and the compiler emits setnp alongside ucomisd.
    Cause: on unordered (NaN) operands, ucomisd sets ZF = PF = CF = 1; checking ZF alone cannot distinguish NaN from equality.
    Fix: check PF (jp/setnp) before deciding equality, or pair ucomisd with both sete and setnp.

Floating-point ABI cheat sheet. The full System V ABI rules live in lesson 18, but the core rule is simple: integer/pointer arguments go in rdi, rsi, rdx, …, floating-point parameters (float/double) go in xmm0–xmm7, and a floating-point return value comes back in xmm0.

Lab

Goal. Implement asm_double_sum(const double *values, size_t count) in NASM to sum a double array using scalar SSE2 instructions.

Contract and requirements.

  • Inputs: pointer to the array and element count; an empty array returns +0.0.
  • Output: double sum in xmm0.
  • Called from a C99 test harness compiled with -std=c99 -D_POSIX_C_SOURCE=200809L -Wall -Wextra -Werror -pedantic.
  • Use SSE2 only; neither x87 nor AVX is needed.
  • Any NaN in the input must propagate to the return value rather than being ignored.

Verification criteria.

  1. make -C lessons/16-float-x87-sse2 build test passes.
  2. {1.5, 2.5} returns 4.0, an empty array returns +0.0, and {0.1, 0.2} produces bits 0x3fd3333333333334.
  3. objdump -d -M intel shows addsd and no fld/fstp.
  4. Running under -fsanitize=address,undefined reports zero errors.
Hints, expected output, and walkthrough

Initialize the accumulator to +0.0 with pxor xmm0, xmm0 so it clears the register cleanly without depending on prior contents. Then loop over the array, loading each double into the accumulator with addsd, advancing the pointer by 8 bytes, and decrementing the counter until zero.

For an empty array, the loop executes zero times and returns +0.0. For {0.1, 0.2}, adding left to right matches float_sse.c, producing the exact bits 0x3fd3333333333334 (0.30000000000000004).

addsd propagates QNaN naturally: if any input element is NaN, the result becomes NaN with no extra check required.

Testbed sources, Makefile, and automated tests for this lesson: lessons/16-float-x87-sse2.

Summary

  1. IEEE 754 encodes a floating-point number as sign, biased exponent, and fractional mantissa.
  2. double uses 64 bits, float uses 32 bits, and x87 uses an 80-bit extended format.
  3. fld decrements TOP and pushes onto the eight-slot x87 stack.
  4. A ninth fld with masked exceptions leaves QNaN on top and sets IE, SF, and C1.
  5. SSE2 uses flat xmm registers: addsd and ucomisd address registers by number without a stack pointer.
  6. QNaN is not equal to itself, so double equality requires checking PF in addition to ZF.
Bridge to the Next Lesson
Values are now flowing through xmm registers, yet our assembly object files have been built mostly in isolation. In lesson 17, I unpack global, extern, weak, PLT, and GOT: how the linker stitches modules together and resolves external shared libraries.