gitee.com/quant1x/gox@v1.21.2/encoding/binary/struc/custom_float16_test.go (about) 1 package struc 2 3 import ( 4 "bytes" 5 "encoding/binary" 6 "fmt" 7 "math" 8 "strconv" 9 "strings" 10 "testing" 11 ) 12 13 func TestFloat16(t *testing.T) { 14 // test cases from https://en.wikipedia.org/wiki/Half-precision_floating-point_format#Half_precision_examples 15 tests := []struct { 16 B string 17 F float64 18 }{ 19 //s expnt significand 20 {"0 01111 0000000000", 1}, 21 {"0 01111 0000000001", 1.0009765625}, 22 {"1 10000 0000000000", -2}, 23 {"0 11110 1111111111", 65504}, 24 // {"0 00001 0000000000", 0.0000610352}, 25 // {"0 00000 1111111111", 0.0000609756}, 26 // {"0 00000 0000000001", 0.0000000596046}, 27 {"0 00000 0000000000", 0}, 28 // {"1 00000 0000000000", -0}, 29 {"0 11111 0000000000", math.Inf(1)}, 30 {"1 11111 0000000000", math.Inf(-1)}, 31 {"0 01101 0101010101", 0.333251953125}, 32 } 33 for _, test := range tests { 34 var buf bytes.Buffer 35 f := Float16(test.F) 36 if err := Pack(&buf, &f); err != nil { 37 t.Error("pack failed:", err) 38 continue 39 } 40 bitval, _ := strconv.ParseUint(strings.Replace(test.B, " ", "", -1), 2, 16) 41 tmp := binary.BigEndian.Uint16(buf.Bytes()) 42 if tmp != uint16(bitval) { 43 t.Errorf("incorrect pack: %s != %016b (%f)", test.B, tmp, test.F) 44 continue 45 } 46 var f2 Float16 47 if err := Unpack(&buf, &f2); err != nil { 48 t.Error("unpack failed:", err) 49 continue 50 } 51 // let sprintf deal with (im)precision for me here 52 if fmt.Sprintf("%f", f) != fmt.Sprintf("%f", f2) { 53 t.Errorf("incorrect unpack: %016b %f != %f", bitval, f, f2) 54 } 55 } 56 }