Skip to content

Instantly share code, notes, and snippets.

@Aurora12
Last active July 10, 2025 12:52
Show Gist options
  • Select an option

  • Save Aurora12/f04e13771481616c152d859b8fdede58 to your computer and use it in GitHub Desktop.

Select an option

Save Aurora12/f04e13771481616c152d859b8fdede58 to your computer and use it in GitHub Desktop.
IEEE 754 Double NaN (Not a Number) encoding

Playground

// IEEE 754 NaN:
// https://en.wikipedia.org/wiki/NaN#Encoding

/*
The overall layout of the 64-bit double-precision floating-point number:
  * Sign bit: 1 bit (most significant bit of the entire 64-bit word)
  * Exponent: 11 bits (following the sign bit, most significant first)
  * Significand (Fraction): 52 bits (following the exponent, most significant first)
*/

const experiments: DataView[] = [
  Number.NaN,
  parseFloat("asdf"),
  123/0,
  123%0,
  0/0,
  123 * ("asd" as any),
  Number.NEGATIVE_INFINITY,
  Number.POSITIVE_INFINITY,
  Math.PI
].map(i => {
  const v = new DataView(new ArrayBuffer(8));
  v.setFloat64(0, i);
  return v
})

function print64(value64: DataView): string {
  const str64 = new Array<string>(8)
    .fill("")
    .map((_, index) => value64.getUint8(index).toString(2).padStart(8, "0"))
    .join("");
  return [
    str64[0], // Sign
    str64.substring(1, 12), // Exponent
    str64.substring(12), // Mantissa
    `(${Number.parseInt(str64.substring(12), 2)})`
  ].join(" ")
}

experiments.forEach((i, index) => console.log(`${index}`, print64(i)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment