github.com/taubyte/vm-wasm-utils@v1.0.2/ieee754/ieee754.go (about)

     1  package ieee754
     2  
     3  import (
     4  	"encoding/binary"
     5  	"io"
     6  	"math"
     7  )
     8  
     9  // DecodeFloat32 decodes a float32 in IEEE 754 binary representation.
    10  // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#floating-point%E2%91%A2
    11  func DecodeFloat32(r io.Reader) (float32, error) {
    12  	buf := make([]byte, 4)
    13  	_, err := io.ReadFull(r, buf)
    14  	if err != nil {
    15  		return 0, err
    16  	}
    17  	raw := binary.LittleEndian.Uint32(buf)
    18  	return math.Float32frombits(raw), nil
    19  }
    20  
    21  // DecodeFloat64 decodes a float64 in IEEE 754 binary representation.
    22  // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#floating-point%E2%91%A2
    23  func DecodeFloat64(r io.Reader) (float64, error) {
    24  	buf := make([]byte, 8)
    25  	_, err := io.ReadFull(r, buf)
    26  	if err != nil {
    27  		return 0, err
    28  	}
    29  	raw := binary.LittleEndian.Uint64(buf)
    30  	return math.Float64frombits(raw), nil
    31  }