util.go 1006 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package util
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "math"
  6. "strconv"
  7. "unsafe"
  8. )
  9. //https://github.com/golang/go/issues/2632#issuecomment-66061057
  10. func Float64frombytes3(data []byte) (theFloat float64, err error) {
  11. // data := make([]byte, len(byt))
  12. // copy(data, byt)
  13. unsafeString := func(b []byte) string {
  14. return *(*string)(unsafe.Pointer(&b))
  15. }
  16. theFloat, err = strconv.ParseFloat(unsafeString(data), 64)
  17. // theFloat, err = strconv.ParseFloat(string(data), 64)
  18. Check(err)
  19. // fmt.Println("theFloat", theFloat)
  20. // if theFloat == 0. {
  21. // err = errors.New("out = 0")
  22. // }
  23. return
  24. }
  25. //https://github.com/golang/go/issues/2632#issuecomment-66061057
  26. func Float64frombytes4(byt []byte) (theFloat float64, err error) {
  27. // data := make([]byte, len(byt))
  28. // copy(data, byt)
  29. if len(byt) < 8 {
  30. data := make([]byte, 8)
  31. copy(data, byt)
  32. }
  33. bits := binary.LittleEndian.Uint64(byt)
  34. theFloat = math.Float64frombits(bits)
  35. return
  36. }
  37. func Check(e error) {
  38. if e != nil {
  39. fmt.Println(e)
  40. }
  41. }