Skip to content
systemcoding.dev
Virtualization

NaN Boxing: Packing Values Into 64-Bit Doubles

NaN boxing hides pointers, booleans and nil inside the unused payload bits of a 64-bit double, so a VM value fits in one machine word with no tag field.

7 min read
Summarize in AI
Flat illustration of a hex dump with one byte highlighted, with the QEMU, C and Python logos.

A dynamically typed VM needs every value to say what it is. The textbook answer is a tagged struct: a type byte plus an eight-byte payload, which the compiler pads to 16 bytes. Every array of values, every stack slot and every constant table doubles in size just to carry a tag. NaN boxing removes the tag by hiding it inside a place a double never uses. The result is an eight-byte value that is either a real number or a pointer, a boolean or nil, told apart by looking at a few high bits. This post builds the encoding in C11, explains why it works on x86-64 and arm64, and ends with the two traps that bite first: hardware-generated NaNs and pointers wider than 48 bits.

Why a double has room to spare

An IEEE 754 binary64 value has 1 sign bit, 11 exponent bits and 52 mantissa bits. When all eleven exponent bits are one and the mantissa is zero, the value is infinity. When the exponent is all ones and the mantissa is non-zero, the value is a NaN, "not a number". The standard does not give any meaning to the specific mantissa bits of a NaN beyond one convention: the top mantissa bit says whether it is a quiet NaN (set) or a signalling one (clear). That leaves 51 mantissa bits, plus the sign bit, that no arithmetic result will ever depend on.

So a 64-bit word has two kinds of contents. If the exponent bits are not all ones, it is an ordinary double and you use it directly. If the exponent bits are all ones and the quiet bit is set, the word is a quiet NaN, and you can store up to 51 bits of your own data in it. No floating point instruction will ever misread it, because a NaN propagates as a NaN. You are borrowing a range of bit patterns that carry no numeric information.

The 64-bit layout, from the top bit down, looks like this.

Text
bit 63        sign
bits 62..52   exponent (all ones for NaN)
bit 51        quiet bit (1 for a quiet NaN)
bits 50..0    payload you control

The encoding used by most small VMs

Pointers on x86-64 and on arm64 under Linux user space use at most 48 bits of virtual address, so a pointer fits comfortably in the 51 payload bits. Singleton values such as nil, true and false need only a couple of bits. The encoding that the book Crafting Interpreters popularised sets bits 62 to 50 as the "this is a boxed value" mask and uses the sign bit to separate pointers from singletons.

nanbox.hc
#include <stdint.h>
#include <stdbool.h>
#include <string.h>

typedef uint64_t Value;

#define SIGN_BIT ((uint64_t)0x8000000000000000)
#define QNAN     ((uint64_t)0x7ffc000000000000)

#define TAG_NIL   1
#define TAG_FALSE 2
#define TAG_TRUE  3

#define NIL_VAL    ((Value)(QNAN | TAG_NIL))
#define FALSE_VAL  ((Value)(QNAN | TAG_FALSE))
#define TRUE_VAL   ((Value)(QNAN | TAG_TRUE))

static inline bool is_number(Value v)  { return (v & QNAN) != QNAN; }
static inline bool is_nil(Value v)     { return v == NIL_VAL; }
static inline bool is_bool(Value v)    { return (v | 1) == TRUE_VAL; }
static inline bool is_object(Value v)  { return (v & (QNAN | SIGN_BIT)) == (QNAN | SIGN_BIT); }

static inline Value number_val(double d) {
    Value v;
    memcpy(&v, &d, sizeof v);
    return v;
}

static inline double as_number(Value v) {
    double d;
    memcpy(&d, &v, sizeof d);
    return d;
}

static inline Value bool_val(bool b)   { return b ? TRUE_VAL : FALSE_VAL; }
static inline bool  as_bool(Value v)   { return v == TRUE_VAL; }

static inline Value object_val(void *p) {
    return (Value)(SIGN_BIT | QNAN | (uint64_t)(uintptr_t)p);
}

static inline void *as_object(Value v) {
    return (void *)(uintptr_t)(v & ~(SIGN_BIT | QNAN));
}

Three things in that header are worth reading slowly. First, is_number asks whether the two mask bits are not both set. A real double never has all of bits 62 to 50 set unless it is one of the NaNs we reserved, so the test is one AND and one compare. Second, is_bool works because TRUE_VAL is FALSE_VAL with the low bit set, so OR-ing one into any boolean gives TRUE_VAL. Third, the conversion between double and uint64_t goes through memcpy. A cast through a pointer violates strict aliasing in C11, and the compiler turns the memcpy of eight bytes into a single register move anyway.

A complete program that uses it

This program stores a number, a boolean, nil and a heap string in four Value slots and prints what each one is.

nanbox.cc
#include <stdio.h>
#include "nanbox.h"

static void show(Value v) {
    if (is_number(v))      printf("number %g\n", as_number(v));
    else if (is_nil(v))    printf("nil\n");
    else if (is_bool(v))   printf("bool %s\n", as_bool(v) ? "true" : "false");
    else if (is_object(v)) printf("object \"%s\"\n", (const char *)as_object(v));
}

int main(void) {
    static const char name[] = "box";
    Value slots[4] = {
        number_val(3.25),
        bool_val(true),
        NIL_VAL,
        object_val((void *)name),
    };
    for (int i = 0; i < 4; i++) show(slots[i]);
    printf("sizeof(Value) = %zu\n", sizeof(Value));
    return 0;
}
Text
number 3.25
bool true
nil
object "box"
sizeof(Value) = 8

Compile it with gcc -std=c11 -O2 nanbox.c -o nanbox on GCC 14. The final line is the point of the whole technique: eight bytes for any value, where a tagged struct would be sixteen. A VM that keeps its stack, its constant pool and its table entries as arrays of Value moves half the memory, and the CPU loads one word instead of two.

Trap one: the NaN your CPU produces on its own

Boxing only works if no arithmetic result can accidentally look like a boxed value. That is the reason for the odd constant 0x7ffc000000000000. When x86-64 SSE computes 0.0 / 0.0, it produces the "real indefinite" quiet NaN, whose bit pattern is 0xFFF8000000000000. That has the exponent bits and the quiet bit set, but bit 50 is clear, so it fails the (v & QNAN) == QNAN test and is correctly classified as a number. Arm64 produces the default NaN 0x7FF8000000000000, which also has bit 50 clear. Choosing a mask that needs one extra bit set keeps both hardware defaults on the number side.

The danger is the other direction. If you ever load a double from untrusted bytes, for example a serialised constant read from a file, and that double has bit 50 set in a NaN, the VM will read it as a boxed singleton or, with the sign bit set, a pointer it will then dereference. Canonicalise any NaN that comes from outside: after reading a double, if d != d, replace it with a known-safe NaN such as the default one.

nanbox_load.cc
#include <math.h>
#include <stdio.h>
#include "nanbox.h"

Value load_number(double d) {
    if (isnan(d)) d = NAN;           // replace any payload with the default NaN
    return number_val(d);
}

int main(void) {
    uint64_t evil = 0xFFFC000000000000;   // sign set, bit 50 set: looks like a pointer
    double d;
    memcpy(&d, &evil, sizeof d);
    Value raw = number_val(d);
    Value safe = load_number(d);
    printf("raw is_object:  %d\n", is_object(raw));
    printf("safe is_object: %d\n", is_object(safe));
    return 0;
}
Text
raw is_object:  1
safe is_object: 0

Here NAN from <math.h> is a quiet NaN with an implementation-defined payload, and on GCC for x86-64 it is 0x7FF8000000000000, which has bit 50 clear. If you want to be sure on every compiler, compare against the mask after the replacement and assert on it.

Trap two: pointers wider than 48 bits

The encoding assumes the pointer's top 16 bits are zero. That is true for user-space addresses with four-level paging on x86-64 and the default 48-bit virtual address space on arm64 Linux. It stops being true if the process opts into larger address spaces. Linux on x86-64 with five-level paging, and arm64 with 52-bit virtual addresses, only hand out addresses above the 48-bit line when a process asks for them with a hint address to mmap, per the kernel's documentation for each architecture. A VM that never passes such a hint never sees them, but a VM that is embedded in a process that does will break in confusing ways. If that matters to you, assert that ((uint64_t)p >> 48) == 0 in object_val during development, and fail loudly.

Pointer tagging is the cheaper cousin of the same idea: align your objects to 8 bytes and use the low three bits as a tag. It handles integers and pointers well, but it does not give you doubles without boxing them, which is the case NaN boxing was built for.

When not to NaN-box

NaN boxing fits when numbers are doubles and you want them unboxed. It costs you real 64-bit integers: the payload has only 51 bits, so a language with a native i64 needs a second representation or a boxed fallback. It also couples the VM to a 48-bit pointer assumption. And it makes debugging harder, because a value in a debugger is a hex word until you write a pretty-printer. If your language is integer-first, or you target a platform with wider pointers, a tagged struct or low-bit pointer tagging is the better trade.

Taggedadvancedc
Share

Keep reading

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

Build an ls Clone with Long Listing Output

Build an ls -l clone in C with opendir, readdir and lstat: mode strings, owner names, sizes and timestamps, using POSIX.1-2024 calls on Linux with glibc 2.41.

7 min read
Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 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.