blog.su21.org   Archives  About

IEEE 754 Floating-Point

遇到几次浮点数的问题需要了解浮点数的内存布局。 还是写下解析 IEEE 754 浮点数标准的代码方便回忆:

package main

import (
	"fmt"
	"math"
	"os"
	"strconv"
)

func main() {
	if len(os.Args) < 2 {
		println("param is required.")
		return
	}

	f64, err := strconv.ParseFloat(os.Args[1], 32)
	if err != nil {
		fmt.Printf("param is not float? parse error: %v", os.Args[1], err)
		return
	}

	f := float32(f64)
	bits := math.Float32bits(f)
	sig := bits >> 31
	exp := int((bits & 0x7f800000) >> 23)
	dig := bits & 0x7fffff

	fmt.Printf("%f = (-1)^%d * 2^(%d) * 1.%b\n", f, sig, exp-127, dig)
	fmt.Printf("%032b\n", bits)
}

Written on May 17, 2019.