Inspect Float Bits Float64bits

Split IEEE-754 doubles into sign, exponent, and mantissa fields with math.Float64bits, and see why bitwise comparison is the only reliable NaN identity test.

GoData Integrity

Code

gosnippet
27 lines
package main

import (
	"fmt"
	"math"
)

func main() {
	// inspect the float bit fields of each IEEE-754 double
	for _, v := range []float64{1, -2.5, 0, math.Inf(1), math.Inf(-1)} {
		bits := math.Float64bits(v)
		sign := bits >> 63
		exponent := (bits >> 52) & 0x7ff
		mantissa := bits & ((1 << 52) - 1)
		fmt.Printf("%-6v sign=%d exp=%03x mantissa=%013x\n", v, sign, exponent, mantissa)
	}

	// 位模式往返:Float64frombits 还原同一个值
	pi := math.Pi
	roundtrip := math.Float64frombits(math.Float64bits(pi))
	fmt.Println("pi roundtrip equal:", pi == roundtrip)

	// NaN 的位模式非唯一:NaN == NaN 恒为 false,等值检查必须换成 IsNaN
	nan := math.NaN()
	fmt.Println("NaN equals itself:", nan == nan)
	fmt.Println("IsNaN:", math.IsNaN(nan))
}

What executes and when

Everything happens inside the function main.

A single loop drives the file — for _, v := range []float64{1, -2.5, 0, math.Inf(1), math.Inf(-1)}.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

The signature doing the primary work is func main()

The demo output is labeled (pi roundtrip equal:, NaN equals itself:, IsNaN:), so the printed lines read as a trace of the operations that ran.

Key statements

for _, v := range []float64{1, -2.5, 0, math.Inf(1), math.Inf(-1)} {
bits := math.Float64bits(v)
sign := bits >> 63
exponent := (bits >> 52) & 0x7ff
mantissa := bits & ((1 << 52) - 1)
fmt.Printf("%-6v sign=%d exp=%03x mantissa=%013x\n", v, sign, exponent, mantissa)
}

Interactive Tools for This Topic

FAQ

What does Inspect Float Bits Float64bits print when run?
No setup needed: run the file and look for labeled lines like `pi roundtrip equal:`, `NaN equals itself:`, `IsNaN:` in the output.